Chitika

Saturday, March 23, 2013

Validate email using regular expression in javascript

Validate email using JavaScript is mandatory when we are developing any web application.
Checking the entered email id is valid using JavaScript(Client Side) will give good performance to the application .

 Take one text box and one button as,
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
  <asp:Button ID="btnSubmit" runat="server" Text="Save" OnClientClick="return validateEmail(txtEmail);" />

To use HTML controls use
     <input type="submit" value="Submit" onclick="return validateEmail(txtEmail);" />

 Write the JavaScript to validate the entered email as,
 <script type="text/javascript">
        function validateEmail(id) {          
            var email = id.value;
            var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
            // var emailPattern = /^[a-zA-Z0-9._-]+@gmail.com+$/;
            if (emailPattern.test(email)) {
                alert("Entered email Id is : " + email);
                return true;
            } else {
                alert("Enter valid email Id.");
                return false;
            }
        }
    </script>

The above code is used to check any email , weather it is valid or not.
If you want to validate only specific domain emails we need to write separately.
For example , if we want to allow only gmail email id's then use below,
 var emailPattern = /^[a-zA-Z0-9._-]+@gmail.com+$/;
instead of   var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

Observe that here we are using regular expression to validate email id.

Info: Regular expressions are one of the best and easiest way to check any format you want.
If you observe the jquery files which has validations, that can be achieved using regular expressions.
By using regular expressions we can minimize the number of lines code we need to write.

See more articles on  JavaScript 







No comments:

Post a Comment