Mr.BK Mr.BK -4 years ago 154
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() {

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 Source

@@ 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})?$/;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download