How to use the includes() method with the entered string In JQuery
In this approach, we will use the includes() method to check whether the entered email contains the @ symbol by passing it in the form of string as parameter to the includes() method. It will return true, if the string contains the symbole, else it return false.
Syntax:
string.trim().includes('symbol');
Example: The below example will explain the use of the includes() method to validate email.
HTML
<!DOCTYPE html> < html > < head > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" > </ script > < style > body { text-align: center; } .contactform-buttons { background-color: #4CAF50; /* Green */ border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; cursor: pointer; } </ style > < script > $(document).ready(function () { $('#submit').click(function (e) { e.preventDefault(); const name = $('#name').val(); const email = $('#email').val(); if (name === '' || email === '') { $('#invalid_email').text("Input Fields can not be Empty!!"); $('#invalid_email').css("color", "red"); return false; } else if (IsEmail(email) === false) { $('#invalid_email').text("Entered Email is not Valid!!"); $('#invalid_email').css("color", "red"); return false; } else{ $('#invalid_email').text("Entered Email is Valid!!"); $('#invalid_email').css("color", "green"); return true; } return false; }); }); function IsEmail(email) { if (!email.trim().includes('@') || email.trim().includes(',')) { return false; } else { return true; } } </ script > </ head > < body > < center > < h1 style = "color:green" >w3wiki</ h1 > < form action = "" method = "post" id = "contactform" > < label for = "name" >Name:</ label > < input name = "name" id = "name" type = "text" autocomplete = "off" placeholder = "Please enter your name" class = "contact-input" > < br />< br /> < label for = "email" >Email :</ label > < input name = "email" id = "email" type = "text" autocomplete = "off" placeholder = "Please enter your email" class = "contact-input" > < p class = "error" id = "invalid_email" > </ p > < br /> < input type = "submit" class = "contactform-buttons" id = "submit" value = "Check email validity" /> </ form > < div id = "correct" style = "color:gray;" > </ div > </ center > </ body > </ html > |
Output:
How to validate Email Id in jQuery ?
The task is to validate an email using jQuery. There are a few parameters to get the refined email one of them is to check whether the email contains the @ symbol or not. We can check this out using the following methods in jQuery:
Table of Content
- Using the Regular Expression to validate the entered email
- Using the includes() method with the entered string