Mr.BK Mr.BK - 3 months ago 31
jQuery Question

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; }

});
});

Answer

@@ 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})?$/;