Sometimes most of the registration and login page need to validate email. In this example you will learn simple email validation.
First take a text input in html and a button input like this
<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='checkEmail();'/>
<script>
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>
you can also check using this regular expression
<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='checkEmail();'/>
<script>
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>
Check this demo output which you can check here
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='checkEmail();'/>
if email invalid then give alert message , if valid email then no alert message .
for more info about regular expression
https://www.w3schools.com/jsref/jsref_obj_regexp.asp
hope it will help you