regex - How to validate email address in JavaScript? -
how can email address validated in javascript?
using regular expressions best way. can see bunch of tests here (taken chromium)
function validateemail(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-za-z\-0-9]+\.)+[a-za-z]{2,}))$/; return re.test(email); }
here's example of regular expresion accepts unicode:
var re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
but keep in mind 1 should not rely upon javascript validation. javascript can disabled. should validated on server side well.
here's example of above in action:
function validateemail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-za-z\-0-9]+\.)+[a-za-z]{2,}))$/; return re.test(email); } function validate() { $("#result").text(""); var email = $("#email").val(); if (validateemail(email)) { $("#result").text(email + " valid :)"); $("#result").css("color", "green"); } else { $("#result").text(email + " not valid :("); $("#result").css("color", "red"); } return false; } $("#validate").bind("click", validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <p>enter email address:</p> <input id='email'> <button type='submit' id='validate'>validate!</button> </form> <h2 id='result'></h2>
Comments
Post a Comment