简体   繁体   中英

javascript validation of single quotes

I have a password field in my registration form. The following is the code for javascript validation.

if(document.getElementById('txtPassword').value == '' || document.getElementById('txtPassword').value == 'Password' ){
            alert("Please enter Password");
            document.getElementById('txtPassword').focus();
            return false;
        }


      else if (document.getElementById('txtPassword').value.length < 8)
       {
               alert('Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number');
               return false;
       }


      else if ( (! document.getElementById('txtPassword').value.match(/[a-z]/) ) || (! document.getElementById('txtPassword').value.match(/[A-Z]/) ) ) {
               alert('Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number');
               return false;
       }


      else if (!document.getElementById('txtPassword').value.match(/\d+/)) {
               alert('Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number');
               return false;
       }

        else if (document.getElementById('txtPassword').length < 8)
       {
               alert('Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number');
               return false;
       }

I need to check for single quotes. If the user enters single quotes in the password field and hit enter the error "Avoid single quotes in this filed" should popup.

How to do that?

else if (document.getElementById('txtPassword').value.indexOf("'") != -1) {
    alert("Avoid single quotes in this field");
    return false;
}

here is a simple test case. If you make an html page, put this in the head tag, open it in a browser, you'll see it works:

var value1 = "abc'def";
var value2 = "abcdef";
if(value1.indexOf("'") != -1)
    alert(value1 + " contains a '");
else
    alert(value1 + " does not contain a '");
if(value2.indexOf("'") != -1)
    alert(value2 + " contains a '");
else
    alert(value2 + " does not contain a '");

Use this regex for password check

^(?=.*\d)(?=.*[a-zA-Z]).{8,}

Currently you are doing lot of validation checks, to avoid those just use above regex.

if (! /^(?=.*\d)(?=.*[a-zA-Z]).{8,}/.test(txtPass)) {
    flag = false;
}
else if(txtPass.indexOf("'") != -1) {
    flag = false;
}

if (!flag)
    alert("Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number");

Refer LIVE DEMO

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