I have JavaScript that validates whole email once entered:
function ValidateEmail(inputText)
{
var mailformat = /^[a-zA-Z0-9.!#$%&’* /=?^_`{|}~-] @[a-zA-Z0-9-] (?:\.[a-zA-Z0-9-] )*$/
if(inputText.value.match(mailformat))
{
alert("This is not a valid email address");
return false;
}
}
But how to check if single character is valid for email? So I want to prevent users to enter bad email characters. So function param would be these and should return false only if invalid character present:
m
my
mya
....
myaddress
....
myaddress@mail.com
CodePudding user response:
great answer: https://stackoverflow.com/a/46181/3764369
issues follows RFC 5322 https://emailregex.com/
w3 code example:
function ValidateEmail(inputText)
{
var mailformat = /^\w ([\.-]?\w )*@\w ([\.-]?\w )*(\.\w{2,3}) $/;
if(inputText.value.match(mailformat))
{
alert("Valid email address!");
document.form.email.focus();
return true;
}
else
{
alert("You have entered an invalid email address!");
document.form.email.focus();
return false;
}
}
CodePudding user response:
You could test the individual characters your user submits with a function like this one shown below, since the allowable characters are limited to letters (a-z), numbers, underscores, periods, and dashes.
/* function that validates input for only email friendly characters */
function validateEmailChars(input) {
var validCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@._-';
for (var i = 0; i < input.length; i ) {
if (validCharacters.indexOf(input[i]) === -1) {
return false;
}
}
return true;
}
var testString1 = 'm'
var testString2 = 'my'
var testString3 = 'mya';
var testString4 = '[email protected]';
console.log(validateEmailChars(testString1));
console.log(validateEmailChars(testString2));
console.log(validateEmailChars(testString3));
console.log(validateEmailChars(testString4));
//should all return true
var testString5 = '[email protected]';
console.log(validateEmailChars(testString5));
//should return false
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>