Home > DeveloperSection > Forums > How to email validation regex in C# and javascript?
Sanjay Sharma
Sanjay Sharma

Total Post:45

Points:315
Posted on    January-19-2015 10:15 PM

 ASP.Net C#  JQuery  JavaScript  Email Integration  Regex 
Ratings:


 1 Reply(s)
 648  View(s)
Rate this:

I have ASP.NET project and I need to check is email correct or not. I always using that script, but it fails with asp.net, because @ is bad symbol.

function emailvalidate(e)

{

    var b=/^[^@\s]+@[^@\.\s]+(\.[^@\.\s]+)+$/;

    return b.test(e);

}

How can I fix this? And its important to check email by JavaScript, not ASP.NET or C#.

P.S. Im really new with ASP.NET and JavaScript RegEx.



Chintoo Semi

Total Post:135

Points:947
Posted on    January-19-2015 11:43 PM

Are you using the Razor view engine? If so you will need to escape those @ symbols if you are adding this script to the cshtml file itself

function emailvalidate(e)

{

    var b=/^[^@@\s]+@@[^@@\.\s]+(\.[^@@\.\s]+)+$/;

    return b.test(e);

}

or you can wrap the regular expression in @Html.Raw as deherch mentioned:

var b = @Html.Raw(@"/^[^@\s]+@[^@\.\s]+(\.[^@\.\s]+)+$/");

you can also add this function to a script file with all your other common JS functions. This way you do not need to escape the razor syntax at all.

Win mentions that you want to use server-side validation. I would say best to use both. Client-side validation can stop it from ever hitting the server in the first place. And server-side validation because you can never trust what a client passes in.


Don't want to miss updates? Please click the below button!

Follow MindStick