简体   繁体   中英

Alphanumeric password validation in javascript

I have written function in javascript for alphanumeric password validation in jsp and calling that function on onkeypress event of textbox but not working.

 function alphanumeric(inputtxt) { var mypswd = document.getElementById(inputtxt).value; mypswd = mypswd.trim(); if (mypswd == "" || mypswd == null) { alert("Please enter password"); } else if (!mypswd.match((/^(?=.\\d)(?=.[az])(?=.*[AZ])[0-9a-zA-Z]{8,}$/)) { alert(" password must be alphanumeric"); } } 
 <form name="form1" method="post" action="Register">Username : <br> <input type="text" name="uname" onkeypress="return checkSpcialChar(event)" onkeydown=" alphanumeric(inputtxt)" /> <br/>Password : <br> <input type="password" name="pwd" onkeypress="return checkSpcialChar(event)" /> <br/> <br> <input type="submit" name="action" value="Submit" onsubmit="check()" /> <input type="submit" value="Back" /> </form> 

please help.

I changed your code a little as some of it was not required for the final outcome you wanted.

The main points are.

onkeyup="alphanumeric(this)"

You can pass in the element that the event was bound to using this . Also I changed the event to onkeyup so you can validate the currently typed character.

When you are getting the value you can then use that element to get the current value.

var mypswd = input.value.trim()

Alerts are really annoying and they block any further execution of the script or interaction with the page, so I put in a div that contains a message so the user get's live feedback of the status of their password.

If you just want alfanumeric validation you can greatly simplify your regular expression to /[^a-z0-9]+/i it's simply checking for any non alfanumeric characters.

 const message = document.querySelector('.message') function alphanumeric(input) { var mypswd = input.value.trim() if (mypswd == "" || mypswd == null) { message.innerHTML = "Please enter password" } else if (mypswd.match(/[^a-z0-9]+/i)) { message.innerHTML = "password must be alphanumeric" } else { message.innerHTML = "All good in the hood" } } 
 <form name="form1" method="post" action="Register"> <div class="message">Please enter a password</div> Passsword : <input type="text" name="pword" id="pword" onkeyup=" alphanumeric(this)" /> </form> 

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