Mr.BK
Mr.BK

Reputation: 61

Email validation regular expression in cshtml using jquery pops error

While validating email textbox using regex and jquery in shtml page, error pops showing issue with regex as it contains "@" in the regex.

$(document).ready(function() {

$('#btn-submit').click(function() { 

    $(".error").hide();
    var hasError = false;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;   //"@" in regex is the issue

    var emailaddressVal = $("#UserEmail").val();
    if(emailaddressVal == '') {
        $("#UserEmail").after('<span class="error">Enter email address.</span>');
        hasError = true;
    }

    else if(!emailReg.test(emailaddressVal)) {
        $("#UserEmail").after('<span class="error">Enter a valid email address.</span>');
        hasError = true;
    }

    if(hasError == true) { return false; }

   });
});

Upvotes: 3

Views: 32429

Answers (3)

mosborn1987
mosborn1987

Reputation: 69

I had issues with the '@' in the cshtml file. I had to use '@@' instead.

The following function worked nicely...

function validateEmail(emailInput) {
    // Regex
    var emailReg = /^[\w-]+(\.[\w-]+)*@@([\w-]+\.)+[a-zA-Z]{2,7}$/;

    // Test
    return emailReg.test(emailInput);
}

Upvotes: 1

oleksiy
oleksiy

Reputation: 11

use utf-8 code instead of @

/^([\w-\.]+\u0040([\w-]+\.)+[\w-]{2,4})?$/

Upvotes: 1

Satpal
Satpal

Reputation: 133423

@@ is escape sequence in MVC, it will render as @

var emailReg = /^([\w-\.]+@@([\w-]+\.)+[\w-]{2,4})?$/;

above statement will be rendered as

var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

Upvotes: 15

Related Questions