i'm creating a login system and i'm trying to validate email input. Validation is working just fine but there is a problem when the email is .info domain example([email protected]), Which seems to be a valid domain, but the system mark it as invalid.Can you have a look please?
If you wondering about onkeypress event i'm using it to prevent empty spaces and on copy/paste as well.
This is the validation code
$('#email').keyup(function () {
if ($("#email").val().match(/^\w ([\.-]?\w )*@\w ([\.-]?\w )*(\.\w{2,3}) $/)) {
$("#emailmessage").html('Email is valid!');
} else {
$("#emailmessage").html('This is invalid email!');
}
});
<input type="email" placeholder="E-mail..." id="email" name="email" onkeypress=" return event.keyCode || event.which, event.keyCode != 32 && event.which != 32" onpaste="return false;">
<div id="emailmessage"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
CodePudding user response:
The issue is here \w{2,3}
you have it limited to only allow to 2 or 3 letters, change it to \w{2,4}
$('#email').keyup(function() {
if ($("#email").val().match(/^\w ([\.-]?\w )*@\w ([\.-]?\w )*(\.\w{2,4}) $/)) {
$("#emailmessage").html('Email is valid!');
} else {
$("#emailmessage").html('This is invalid email!');
}
});
<input type="email" placeholder="E-mail..." id="email" name="email" onkeypress=" return event.keyCode || event.which, event.keyCode != 32 && event.which != 32" onpaste="return false;">
<div id="emailmessage"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
Here is an improved version of your code I've also removed jQuery
const email = document.getElementById('email');
const message = document.getElementById('emailmessage');
email.addEventListener('keyup', e => {
const validEmail = e.currentTarget.value.match(/^\w ([\.-]?\w )*@\w ([\.-]?\w )*(\.\w{2,4}) $/)
message.textContent = validEmail ? 'Email is valid!' : 'This is invalid email!'
})
email.addEventListener('keypress', e => e.code === 'Space' && e.preventDefault())
email.addEventListener('paste', e => e.preventDefault())
<input type="email" placeholder="E-mail..." id="email" name="email">
<div id="emailmessage"></div>