Compilation error when using Regex expression with jQuery in ASP.NET MVC

I am trying to check email as below with jQuery in asp.net mvc as below.

<script type="text/javascript">
   function validateEmail(sEmail) {
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (filter.test(sEmail)) {
        return true;
    }
    else {
        return false;
    }
      $(document).ready(function() {
   $('#create').click(function() {
        var sEmail = $('#UserName').val();
        if ($.trim(sEmail).length == 0) {
            alert('Please enter valid email address');
            e.preventDefault();
        }
        if (validateEmail(sEmail)) {
            alert('Email is valid');
        }
        else {
            alert('Invalid Email Address');
            e.preventDefault();
        }
    });
});
    });
</script>

      

While rendering the view, I got a compilation error Unexpected '\' character in this regex appearance. How can I resolve this error?

+3


source to share


2 answers


I got the same error. Here is the answer. I like. Use @@ instead of @.

In your case, this is:



var filter = /^([\w-\.]+)@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

      

+9


source


You have an oddity with your curly braces. In particular, you did not close the validateEmail function correctly. Here is the adjusted Javascript code:

    function validateEmail(sEmail) {
        var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
        if (filter.test(sEmail)) {
            return true;
        }
        else {
            return false;
        }
    }
    $(document).ready(function() {

        $('#create').click(function() {
            var sEmail = $('#UserName').val();
            if ($.trim(sEmail).length == 0) {
                alert('Please enter valid email address');
                e.preventDefault();
            }
            if (validateEmail(sEmail)) {
                alert('Email is valid');
            }
            else {
                alert('Invalid Email Address');
                e.preventDefault();
            }
        });
    });

      



EDIT: Also, unrelated, you can make this validateEmail function a little more concise since test returns a boolean. See below:

    function validateEmail(sEmail) {
        var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

        return filter.test(sEmail);
    }

      

0


source







All Articles