I've set the pattern for my javascript code and have error messages set up, but can't seemt o figure out how to force it to take ""@""."" as a format as it will accept single letters as valid for some reason

  function myFunction3() {
    var message, x, j;
    message = document.getElementById("message3");
    message.innerHTML = "";
    x = document.getElementById("Email").value;
    try {
    if (x == "") throw "Required Field";
    if (x =  /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/) throw "Valid";


      }
   catch(err) {
    message.innerHTML = err;

  }
  }

1 Answers

0
CTOverton On Best Solutions

What you need to do is setup a valid regex test. This looks something like this:

function myFunction3() {
    let message, x, j;
    let RegExp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; // Change this
    message = document.getElementById("message3");
    message.innerHTML = "";
    x = document.getElementById("Email").value;

    if (x === '') return 'Required Field';
    else if (RegExp.test(x)) return 'Valid';
    else return 'Value not valid';
}

I find using a regex tool like https://regexr.com/ is really helpful for getting the right validation. Since you only specify "accept single letters as valid for some reason" I'm not sure what exact expression you need, but if you elaborate I can help you create one :)