validate password length after user leave password field - javascript

I want to check if the password length is at least 8 characters or not, when the user leaves the password field or press tab key.
How can i do this?
My code for password is shown below.
<input type="password" name="password" id="pass1" placeholder="password"/>

Use the jquery blur method for this.
$('#pass1').on('blur', function(){
if(this.value.length < 8){ // checks the password value length
alert('You have entered less than 8 characters for password');
$(this).focus(); // focuses the current field.
return false; // stops the execution.
}
});
Fiddle for Demo

You can use javascript onchange event as below
and script code callfunction() as
function callfunction()
{
var textBox = document.getElementById("pass1");
var textLength = textBox.value.length;
if(textBox.value=='' || textLength<=8)
{
alert('Please enter correct password');
}
}

try this:
$('#pass1').on('blur', function(){
if($(this).val().length > 8){
alert('safe!');
}
});
here is an example: http://jsfiddle.net/ACK2f/

Password validation can use several rules, I used a service but the code inside the function can be reusable:
_validatePassword = function (validateUserNameRules, Model)
{
//bolean parameter validateUserNameRules -> true/false
//this method recive a model like this:
//Model.userName -> string
//Model.password -> string
//Model.password2 -> String
var validationResult = {
ResultId: 1, //1 success
Message: "Password is correct."
};
if (validateUserNameRules && Model.userName == "") {
validationResult.ResultId = 2;
validationResult.Message = "Error: User name cannot be blank.";
return (validationResult);
}
var re = /^\w+$/;
if (validateUserNameRules && !re.test(Model.userName)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: Username must contain only letters, numbers and underscores.";
return (validationResult);
}
if (Model.password != "" && Model.password == Model.password2) {
if (Model.password.length < 6) {
validationResult.ResultId = 2;
validationResult.Message = "Error: Password must contain at least six characters.";
return (validationResult);
}
if (validateUserNameRules && Model.password == Model.userName) {
validationResult.ResultId = 2;
validationResult.Message = "Error: Password must be different from the Account Name.";
return (validationResult);
}
re = /[0-9]/;
if (!re.test(Model.password)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: password must contain at least one number (0-9).";
return (validationResult);
}
re = /[a-z]/;
if (!re.test(Model.password)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: password must contain at least one lowercase letter (a-z).";
return (validationResult);
}
re = /[A-Z]/;
if (!re.test(Model.password)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: password must contain at least one uppercase letter (A-Z).";
return (validationResult);
}
} else {
validationResult.ResultId = 2;
validationResult.Message = "Error: Please check that you've entered and confirmed your password.";
return (validationResult);
}
return (validationResult); //success password validation!!
};

Related

Validate password - must contain 2 capital letters

Can someone tell me why this function doesn't work? the password length and the check of number work perfectly. But it is something wrong with the check of big capitals...
function validera() {
var passw = document.getElementById("User-Password").value;
var upper = /[A-Z]/ ;
var number = /[0-9]/;
if (passw.length < 6 || !number.test(passw) || !upper.test(passw)) {
if (passw.length < 6) {
alert("Please make sure password is longer than 6 characters.")
return false;
}
var counter = 0;
var i;
for(i = 0; i < passw.length; i++){
passw.charAt(i)
if(upper.test(passw.charAt(i))){
counter++;
break;
}
}
if( counter < 2 ){
alert("Please make sure password includes 2 capital letters")
return false;
}
if (!number.test(passw)) {
alert("Please make sure Password Includes a Digit")
return false;
}
} else {
alert("Account created")
}
Or do I have to use regex?
If you are planning to use regex to find two capital letters then you can use like
\w*[A-Z]\w*[A-Z]\w*
Test this here on regextester
Here Check it out Fiddle
CreateRandomPassword(Length, isUpperAlpha, isLowerAlpha, isNumaric ,SpecialChars)
I have developed easy function to generate password
Here's a function that returns an object with a message and a boolean.
Example snippet:
function testPassword(pwd) {
if (pwd.length <= 6)
return { valid: false, message: "Please make sure password is longer than 6 characters." };
if(!/[A-Z].*[A-Z]/.test(pwd))
return { valid: false, message: "Please make sure password includes 2 capital letters" };
if (!/\d/.test(pwd))
return { valid: false, message: "Please make sure Password Includes a Digit" };
if (/\s/.test(pwd))
return { valid: false, message: "Please only use visible characters" };
return { valid: true, message: "Valid Password" };
}
console.log(testPassword('Val1dPassword'));
console.log(testPassword('SH0rt'));
console.log(testPassword('No2capitals'));
console.log(testPassword('NoDigits'));
console.log(testPassword('Has\tat least 1 WhiteSpace'));
Then your function can be simplified.
function validera() {
let passw = document.getElementById("User-Password").value;
let check = testPassword(passwd);
if (check.valid) {
alert(check.message);
return false;
}
else {
alert("Account created")
}
}

How to validate a password in javascript

This is the code I wrote, it returns the alert every time even if the password is within the range(4-12).
function PasswordCheck() {
var str = document.getElementById("Password");
if (str > 4 && str < 12) {
return true;
} else {
alert("invalid password, your password needs to have 4-12 letters");
return false;
}
}
You need to retrieve the text in your element with value.
Then you want to check the length of your string with the Ā length property of the str string.
function PasswordCheck() {
var str = document.getElementById("Password").value;
if (str.length > 4 && str.length < 12) {
return true;
} else {
alert("invalid password, your password needs to have 4-12 letters");
return false;
}
}
This is because getElementById returns an Element object and not the value directly.

Password with regular password

I have to do the password by this condition for creating password to follow this characteristics :
Contain at least 12 alphanumeric characters.
Contain both upper and lower case letters.
Contain at least one number (for example, 0-9).
Contain at least one special character (for example,!$%^&*()_+|~-=`{}[]:";'<>?,/).
i did this :
<input type="password" required pattern="^(?=.*[a-zA-Z])(?=.*\d)(?=.*
[!##$%^&*()_+])[A-Za-z\d][A-Za-z\d!##$%^&*{}()_=+]{12,}$"
name="password"
nblur="this.setCustomValidity(this.validity.patternMismatch
? 'Password must contain at least 12 characters, including upper
lowercase numbers and least special character' : '');
if(this.checkValidity()) form.password1.pattern = this.value;">
but when i try to put a password and confirm it always return not valid password
Sorry for this question, but with regExpression i put for this characteritics. Thanks in advance.
Write a series of test in JavaScript and control the submit event for your form.
var testPassword = (function() {
var allTests = [];
var minimumAlphaNumericCharacters = 12;
function countAlphanumeric(password) {
var count = password.length - password.replace(/[a-z]|\d/ig, '').length;
if (count < minimumAlphaNumericCharacters) {
return "Too few Alphanumeric Characters! At least " + minimumAlphaNumericCharacters + " nedded, " + count + " found";
}
return true;
}
allTests.push(countAlphanumeric);
function containsUpperAndLowerCharacters(password) {
var test = (password === password.toLowerCase());
if (test) {
return "Must contain both upper and lower case characters";
}
return true;
}
allTests.push(containsUpperAndLowerCharacters);
var minimumDigits = 1;
function containsMinimumDigits(password) {
var test = password.replace(/\D/ig, '').length;
if (test < minimumDigits) {
return "Must contain at least " + minimumDigits + " digits, " + test + " digits found";
}
return true;
}
allTests.push(containsMinimumDigits);
var minimumSpecials = 1;
function containsMinimumSpecials(password) {
var test = password.replace(/\w/ig, '').length;
if (test < minimumSpecials) {
return "Must contain at least " + minimumSpecials + " special symbols, " + test + " special symbols found";
}
return true;
}
allTests.push(containsMinimumSpecials);
return function testPassword(password) {
return allTests
.map(function(test) {
return test(password);
})
.filter(function(test) {
return test !== true;
});
};
})();
//TEST
var form = document.body.appendChild(document.createElement("form"));
var input = form.appendChild(document.createElement("input"));
var output = document.body.appendChild(document.createElement("pre"));
input.onchange = input.onkeyup = form.onsubmit = function(evt) {
var password = input.value.toString();
var test = testPassword(password);
output.textContent = test.join("\n");
if (evt.type == "submit") {
alert((test.length < 1 ? "Good" : "Bad") + " Password");
}
return false;
};

Form Validation Requiring Enter to Continue

Some simple form validation seems to require hitting Enter once the correct value has been added before allowing the visitor to move on. Any way to eliminate that? Here is an example of one of them.
// Makes sure that the email looks valid and contains an #, a . and at least two characters after the dot
function checkEMail(obj) {
var emailFilter = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/ ;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (!emailFilter.test(obj)) {
obj.style.background = 'Yellow';
alert('Please enter a valid email address, then press Enter to continue.');
} else if (!illegalChars.test(obj)) {
obj.style.background = 'Yellow';
alert('The email address contains illegal characters.');
} else {
obj.style.background = 'White';
}
}
Just make a return to true in your "happy flow" in the validation function.
// Makes sure that the email looks valid and contains an #, a . and at least two characters after the dot
function checkEMail(obj) {
var emailFilter = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/ ;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (!emailFilter.test(obj)) {
obj.style.background = 'Yellow';
alert('Please enter a valid email address, then press Enter to continue.');
} else if (!illegalChars.test(obj)) {
obj.style.background = 'Yellow';
alert('The email address contains illegal characters.');
} else {
obj.style.background = 'White';
return true;
}
}
Script with similar type of logic, working example:
function execute(a) {
if(a === 1) {
alert("1");
} else if (a === 2) {
alert("2");
} else {
console.log('lele');
return true;
}
}
execute(3);

If Statement Only Executing Else Part

I have a simple program that validates a sign up form. Basically I reach a problem when one of my "if" statements can only execute the "else" part. If I change the form so that "if" is executed, nothing happens. Below is my code:
function verifyprocedure() {
var originalpassword = document.getElementById("password").value;
var checkpassword = document.getElementById("verifypassword").value;
var emailcheck = document.getElementById("email").value;
var male = document.getElementById("gendermale");
var female = document.getElementById("genderfemale");
var form = document.getElementById("signup");
var emailexist = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (originalpassword == checkpassword) {
if (originalpassword.length < 9) {
if (emailexist.test(emailcheck)) //this is the statement that does not work
{
alert("Hello World!"); //this is whats supposed to be executed
} else { //this is successfully executed
$("#email").notify("Please enter a valid email address.");
}
} else {
$("#password").notify("Passwords must have at least 9 characters.");
}
} else {
$("#verifypassword").notify("Passwords do not match.");
}
}
Did you check whether it is working or not ?
anyway it is working for me,i think your input should be invalid you can use the following code for checking
var originalpassword ="abcdefgh";
var checkpassword = "abcdefgh";
var emailcheck = "arun#gmail.com";
var male ="male";
var emailexist = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (originalpassword == checkpassword) {
alert("hai");
}
if (originalpassword.length < 9) {
if (emailexist.test(emailcheck))
{
alert("Hello World!");
} else {
alert("Please enter a valid email address.");
}
}
Working DEMO
UPDATE
var originalpassword ="abcdefgh";
var checkpassword = "abcdefgh";
var emailcheck = "arun#gmail.com";
var male ="male";
var emailexist = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (originalpassword == checkpassword)
{
alert("hai");
if (originalpassword.length > 9)
{
if (emailexist.test(emailcheck))
{
alert("Hello World!");
}
else
{
alert("Please enter a valid email address.");
}
}
else
{
alert("Passwords must have at least 9 characters.");
}
}
else {
alert("Passwords do not match.");
}
Check this DEMO It will satisfy all conditions.
Note : Check your if condition for password length, if you want the desired output then it will be like if (originalpassword.length > 9)
if (originalpassword.length > 9) {
if (emailexist.test(emailcheck)) //this is the statement that does not work
{
alert("Hello World!"); //this is whats supposed to be executed
} else { //this is successfully executed
$("#email").notify("Please enter a valid email address.");
}
} else {
$("#password").notify("Passwords must have at least 9 characters.");
}

Categories