Validation is commonly defined as the process of checking the values inputted by the user. Commonly it provides a good user experience. If the user inputs any wrong value, It is the developer's responsibility to return a common alert.
The common method to validate an email with Javascript is using regular Expression. To ensure the integrity of your data, Client-side validation should be complemented with server-side validation.
Let's check the following example:
<script type="text/javascript"> function validateEmailInput(input_email) { // Regular expression for a basic email validation const emailRegx = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegx.test(input_email); } // Example usage: const email_to_validate = "test@gmail.com"; if (validateEmailInput(email_to_validate)) { alert("Email is Valid"); } else { alert("Email is not Valid"); } </script>
In the above example, the function validateEmailInput function uses a regular expression to check input email is in the correct format or not.
When the user provides critical Information, then Validation is an essential part. With Javascript code, it can validate name, email, password, etc. This ensures the user's authenticity.
If the email validation on the client side is completed, then processing of data on server side validation is also somewhat faster.
Email Format: personal_data@domain_name
Personal Data Includes: Uppercase (A-Z) and Lowercase letters(a-z) of the alphabet, digits(0-9), characters ( ! # $ % & ' * + - / = ? ^ _ ` { | } ~ ) and the character (.)
Example:
<form> <input type="text" id="email_text" name="email_text"> <button type="submit" onclick="validate()">Submit</button> </form> <script type="text/javascript"> function validate() { var email = document.getElementById('email_text').value; const regx = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if(regx.test(email)){ alert("Email is Valid"); return true; }else{ alert("Email is Invalid"); return true; } } </script>
function validateEmail(email) {
const regex = /^([a-zA-Z0-9_\.-]+)@([a-zA-Z0-9_\.-]+)\.([a-zA-Z]{2,5})$/;
return regex.test(email);
}
This function uses a regular expression to check if the email address is valid. The regular expression checks if the email address has the following format:
@
symbol.You can use this function to validate an email address in your JavaScript code. If the email address is valid, the function will return true
. If the email address is not valid, the function will return false
.