user2051445
user2051445

Reputation: 13

length property in javascript not working properly

i want to restrict the user to enter the password in the range of 6-20 characters. but the function below in not working properly.

 function validatePass(pwd1, pwd2)
 {
var len = document.getElementById('pwd1').value;
if(len.length < 6 || len.length > 20)
{ pwd1.setCustomValidity('Enter 6-20 characters');
}
else if (pwd1.value != pwd2.value || pwd1.value == '' || pwd2.value == '' )
{
        pwd2.setCustomValidity('Password incorrect');
  } 
else 
{
    pwd2.setCustomValidity('');
}
}

the html code is:

<h4>Password</h4></td>
<td><input type="password" name="pwd1" size="30" id="pwd1" required placeholder="Enter 6-20 characters"></td></tr>
<tr><td>
<h4>Confirm Password</h4></td>
<td><input type="password" name="pwd2" id="pwd2" size="30" required onfocus="validatePass(document.getElementById('pwd1'), this);" oninput="validatePass(document.getElementById('pwd1'), this);">
</td></tr>

Upvotes: 0

Views: 413

Answers (2)

Alex
Alex

Reputation: 6149

Try using regular expressions like this:

^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{6,20}$

Source: .NET RegEx to validate password between 6 and 20 characters with at least one upper case letter, one lower case letter and one digit

Here is a full example:

function CheckPassword(inputtxt) 
{ 
var passw = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$/;
if(inputtxt.value.match(passw)) 
{ 
alert('Correct, try another...')
return true;
}
else
{ 
alert('Wrong...!')
return false;
}
}

Source: http://www.w3resource.com/javascript/form/password-validation.php

Upvotes: 0

Eli
Eli

Reputation: 14827

In HTML5, you can use pattern attribute:

<input type="password" pattern=".{6,20}" name="pwd1" size="30" id="pwd1" required placeholder="Enter 6-20 characters"></td></tr>

Upvotes: 1

Related Questions