In this post, we shows you an example to validate email address using regex pattern. In this example, email address validation will work on form submit button event.
Try to run below code to see how js regex email validation works.
jQuery Validate Email with Regex HTML Form Example
First create HTML form with email input field.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <form class="frmContactForm" action="" method="POST"> <div class="frmContactRow"> <div class="label"> Email <span>*</span> <div id="emailmsg" class="validateMsg" data-msg-required=" Invalid email address"></div> </div> <input type="text" id="useremail" name="useremail" onfocusout='return ValidateUserEmail();'> </div> <div class="frmContactRow" align="center"> <button type="Submit" id="frmContactSubmit">Submit</button> </div> </form> |
Now add below Email validation regex jQuery script code in the same HTML form file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
<script> function validate() { var emailField = true; emailField = ValidateUserEmail(); // call validate function if (emailField == false) { $("#useremail").addClass("error-field"); // add error class on email input field valid = false; } return valid; } function ValidateUserEmail() { var valid = true; valid = checkEmailFormat(); return valid; } function checkEmailFormat() { var emailElementId = 'useremail'; var emailDivId = 'emailmsg'; valid = true; var emailRegex = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; var email = $("#" + emailElementId).val(); if ($("#" + emailElementId + ".required").length <= 0 && email == "") { return true; } $("#" + emailDivId).html(" "); var trimEmail = email.trim(); if (!emailRegex.test(trimEmail)) { var message = $("#" + emailDivId).data("msg-required"); $("#" + emailDivId).html(message); valid = false; } return valid; } $(document).ready(function(e) { $(".frmContactForm").on('submit', (function(e) { e.preventDefault(); var form = new FormData(this); var valid = validate(); if (valid == true) { // write AJAX call here, which perform after form submit } })); }); </script> |
Check These Also
Multi Step Form jQuery Bootstrap with Validation
Google reCAPTCHA with Contact Form
Submit Form Without Page Refresh Using jQuery, Ajax and PHP