简体   繁体   中英

JS validation error firing even when no value is being entered

I have a problem where I have 3 input fields. The first field is for the username and the other two fields are for password validation. Now the password fields cannot contain the user name field so I have written the logic to display a message if the password fields contains any part of the user name. However if the user name field has nothing in it, that same validation message is still firing if something is typed in the password field.

Here is the code

Code getting the user name field:

if (document.getElementById("tUserName")) {
        uN = document.getElementById("tUserName").value;
    }
    else {
        uN = "";
    }

The user name field regEx:

containsUsername = new RegExp(uN);

this is the code that is responsible for the validation error message:

if (document.getElementByIdd("tUserName")) {
        if (containsUsername.test(value)) {
            dojo.addClass(dojo.byId('result-userName'), 'hide');  
        }
        else {
            dojo.removeClass(dojo.byId('result-userName'), 'hide');
        }
    }

I'm worried that I must be missing the point here so bear with me if I am....

So you want the validation error not to show when they type in passwords without anything in the username field?

Can you not just check that the username has a value of something other than an empty string before you try running it through the regex?

if (document.getElementById("tUserName")) {
    if (document.getElementById("tUserName").value != '' && containsUsername.test(value)) {
        dojo.addClass(dojo.byId('result-userName'), 'hide');  
    }
    else {
        dojo.removeClass(dojo.byId('result-userName'), 'hide');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM