0

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
John Glabb
  • 1,336
  • 5
  • 22
  • 52
  • Use `mailformat.test(inputText.value)`. See [RegExp.prototype.test()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) – Phil Oct 22 '21 at 04:30
  • 6
    Why don't you use [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email) and save yourself some trouble? – Andy Oct 22 '21 at 04:35
  • @Andy, I think this will only work for client side validation and wont work in server side validation. – user11823877 Oct 22 '21 at 08:28
  • 1
    The OP has `React` as a tag so I assume the email address is coming from there. @user11823877 – Andy Oct 22 '21 at 08:30
  • @Andy, got it. It also has nodejs tag. So just wanted to confirm. also I think we need to add pattern for type="email" to validate. – user11823877 Oct 22 '21 at 08:54
  • @John I think this expression should work for you: ^[A-z0-9]+[@]?[A-z0-9]+[.]?[A-z0-9]+$` – user11823877 Oct 22 '21 at 09:15
  • What's an `email friendly character`, in this context? – ksav Oct 23 '21 at 02:07

1 Answers1

0

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;
  }
}
dzNET
  • 930
  • 1
  • 9
  • 14