jQuery email id validation code for all purposes.

Validating Email ID with jQuery is a bit tricky for newbies if you are not going to use any validation plugin or script. There are some scenarios where you will need to quickly validate the user input field esp. email id and you may not want to use a heavy validation plugin for this small task.

So here is the sample code that you can use to validate the user’s email. You can use this to validate email IDs before taking any actions such as passing data through Ajax calls and etc.

var email = 'test@gmail.com'; // or fetch email value from user input e.g. $('#email_input_field_id').val();
if(email) {
    var requiredRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (email.match(requiredRegex)) {
	//email is valid. You can take action here as per your requirement.
    } else {
	//Email is not valid. Take neccessary step
    }
}

The above function will validate your email id properly without fail. You can create a function using the same above code too just like this –

function validateEmail(email) {
    var requiredRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (email.match(requiredRegex)) {
	return true;
    } else {
	return false;
    }
}

//Now use the function like this
var email = 'test@gmail.com'; // or e.g. $('#email_input_field_id').val();
if(validateEmail(email)) {
    //Email id is valid. Do whatever you want
}else {
    //Invalide email id. Do whatever you want
}

That’s all mate. Hope this will help you to overcome the email validation issue. This is a small piece of code but validates the email id very accurately. Let me know in the comment if you face any issues. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top