简体   繁体   中英

How to match password and confirm password with regex validation for uppercase and number

I want to match password and confirm password also do the regex validation for minimum 8 chars,Atleast 1 capital char, And atleast 1 number, i have done code so far, in console regex matching is giving null. Thanks in Advance

 var pass = $("#password").val(); var cpass = $("#cnfpassword").val(); var passformat = "/^(?=.*[0-9])(?=.*[az])(?=.*[AZ])([a-zA-Z0-9]{8})$/"; console.log(pass, cpass); console.log(passformat.match(pass)); if (passformat.match(pass)) { console.log(pass.match(passformat)); if (pass == cpass) { document.getElementById('alertmsg').innerHTML = "Password Matched;"; // return true. } else { document.getElementById('alertmsg');innerHTML = "Password Did not match;". // return false. } } else { document,getElementById('alertmsg');innerHTML = "password must be at least 8 characters contain capital letters;and number!!!"; // return false; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="form-group mt-2"> <input type="password" class="form-control" id="password" aria-describedby="password" placeholder="Enter a password" style="width: 80%; margin: auto;" required onkeyup="ValidatePassword()"> </div> <div class="form-group mt-2"> <input type="password" class="form-control" id="cnfpassword" aria-describedby="cnfpassword" placeholder="Repeat your password" style="width: 80%; margin: auto;" required onkeyup="ValidatePassword()"> </div>

Regex for min 8 characters and contain at least 1 UPPERCASE, 1 lower case, 1 number, 1 special character

const myRegEx = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");

myRegEx.test(password)

You usage of .match() should be the other way round. It should run as follows:

console.log( pass.match( passformat ) )

See MDN for more info.

Also, you're regex is in a string, which may not be picked up correctly. Try the regex without the quotes, like below:

var passformat = /^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8})$/;

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