1

Why is my validation failing on second attempt here? On first attempt the validation works fine, but on the second run, it will accept inappropriate values in the email field. The first two fields work fine, but the third field will accept any text after the first run. However it only validates if I change the value in the email field, otherwise it will keep displaying the error and failing to validate like it should.

function validate(){

    clearErrors();

    var errorFlag = true;

    var name = document.getElementById("name");

    nameVal = name.value;

    if(nameVal.length === 0){

        var nameError = document.getElementById("nameError");

        nameError.style.display = "block";

        errorFlag = false;
    }

    var phone = document.getElementById("phone")

    var phoneVal = phone.value;

    if(isNaN(phoneVal) || (phoneVal < 1000000000 || phoneVal >10000000000)){

        errorFlag = false;

        var phoneError = document.getElementById("phoneError");

        phoneError.style.display = "block";
    }



    var email = document.getElementById("email");

    var emailVal = email.value;

    var reStr = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$";

    if((reStr.match(emailVal))){

        errorFlag = false;

        var emailError = document.getElementById("emailError");

        emailError.style.display = "block";
    }

    return errorFlag;
}

function clearErrors(){

    var nameError = document.getElementById("nameError");

    nameError.style.display = "none";

    var phoneError = document.getElementById("phoneError");

    phoneError.style.display = "none";

    var emailError = document.getElementById("emailError");

    emailError.style.display = "none";

}
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
Bottlecaps
  • 129
  • 1
  • 2
  • 10

1 Answers1

2

Your validator will fail on the email, because you are feeding a string to .match, when it needs a regex.

You also have to call .match on the email itself, with the regex as the argument.

You also need to negate the return value to check if it does not match, or use .test.

This bit:

var reStr = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$";
if((reStr.match(emailVal))){

Should be replaced with:

var re = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
if(!emailVal.match(re)){

Of if you can't use a regex literal for some reason:

var re = new RegExp("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$", "i");
if(!emailVal.match(re)){

Or using .test instead of .match:

var re = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
if(!re.test(emailVal)){

Note the i for case-insensitive matching, so emails don't have to be entered in all-caps.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171