Javascript regular expression password validation having special characters - javascript

I am trying to validate the password using regular expression. The password is getting updated if we have all the characters as alphabets. Where am i going wrong ? is the regular expression right ?
function validatePassword() {
var newPassword = document.getElementById('changePasswordForm').newPassword.value;
var minNumberofChars = 6;
var maxNumberofChars = 16;
var regularExpression = /^[a-zA-Z0-9!##$%^&*]{6,16}$/;
alert(newPassword);
if(newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars){
return false;
}
if(!regularExpression.test(newPassword)) {
alert("password should contain atleast one number and one special character");
return false;
}
}

Use positive lookahead assertions:
var regularExpression = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{6,16}$/;
Without it, your current regex only matches that you have 6 to 16 valid characters, it doesn't validate that it has at least a number, and at least a special character. That's what the lookahead above is for.
(?=.*[0-9]) - Assert a string has at least one number;
(?=.*[!##$%^&*]) - Assert a string has at least one special character.

I use the following script for min 8 letter password, with at least a symbol, upper and lower case letters and a number
function checkPassword(str)
{
var re = /^(?=.*\d)(?=.*[!##$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
return re.test(str);
}

function validatePassword() {
var p = document.getElementById('newPassword').value,
errors = [];
if (p.length < 8) {
errors.push("Your password must be at least 8 characters");
}
if (p.search(/[a-z]/i) < 0) {
errors.push("Your password must contain at least one letter.");
}
if (p.search(/[0-9]/) < 0) {
errors.push("Your password must contain at least one digit.");
}
if (errors.length > 0) {
alert(errors.join("\n"));
return false;
}
return true;
}
There is a certain issue in below answer as it is not checking whole string due to absence of [ ] while checking the characters and numerals, this is correct version

you can make your own regular expression for javascript validation
/^ : Start
(?=.{8,}) : Length
(?=.*[a-zA-Z]) : Letters
(?=.*\d) : Digits
(?=.*[!#$%&? "]) : Special characters
$/ : End
(/^
(?=.*\d) //should contain at least one digit
(?=.*[a-z]) //should contain at least one lower case
(?=.*[A-Z]) //should contain at least one upper case
[a-zA-Z0-9]{8,} //should contain at least 8 from the mentioned characters
$/)
Example:- /^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{7,}$/

Don't try and do too much in one step. Keep each rule separate.
function validatePassword() {
var p = document.getElementById('newPassword').value,
errors = [];
if (p.length < 8) {
errors.push("Your password must be at least 8 characters");
}
if (p.search(/[a-z]/i) < 0) {
errors.push("Your password must contain at least one letter.");
}
if (p.search(/[0-9]/) < 0) {
errors.push("Your password must contain at least one digit.");
}
if (errors.length > 0) {
alert(errors.join("\n"));
return false;
}
return true;
}

Regex for password:
/^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[a-zA-Z!#$%&? "])[a-zA-Z0-9!#$%&?]{8,20}$/
Took me a while to figure out the restrictions, but I did it!
Restrictions: (Note: I have used >> and << to show the important characters)
Minimum 8 characters {>>8,20}
Maximum 20 characters {8,>>20}
At least one uppercase character (?=.*[A-Z])
At least one lowercase character (?=.*[a-z])
At least one digit (?=.*\d)
At least one special character (?=.*[a-zA-Z >>!#$%&? "<<])[a-zA-Z0-9 >>!#$%&?<< ]

Here I'm extending #João Silva's answer. I had a requirement to check different parameters and throw different messages accordingly.
I divided the regex into different parts and now the checkPasswordValidity(String) function checks each regex part conditionally and throw different messages.
Hope the below example will help you to understand better!
/**
* #param {string} value: passwordValue
*/
const checkPasswordValidity = (value) => {
const isNonWhiteSpace = /^\S*$/;
if (!isNonWhiteSpace.test(value)) {
return "Password must not contain Whitespaces.";
}
const isContainsUppercase = /^(?=.*[A-Z]).*$/;
if (!isContainsUppercase.test(value)) {
return "Password must have at least one Uppercase Character.";
}
const isContainsLowercase = /^(?=.*[a-z]).*$/;
if (!isContainsLowercase.test(value)) {
return "Password must have at least one Lowercase Character.";
}
const isContainsNumber = /^(?=.*[0-9]).*$/;
if (!isContainsNumber.test(value)) {
return "Password must contain at least one Digit.";
}
const isContainsSymbol =
/^(?=.*[~`!##$%^&*()--+={}\[\]|\\:;"'<>,.?/_₹]).*$/;
if (!isContainsSymbol.test(value)) {
return "Password must contain at least one Special Symbol.";
}
const isValidLength = /^.{10,16}$/;
if (!isValidLength.test(value)) {
return "Password must be 10-16 Characters Long.";
}
return null;
}
//------------------
// Usage/Example:
let yourPassword = "yourPassword123";
const message = checkPasswordValidity(yourPassword);
if (!message) {
console.log("Hurray! Your Password is Valid and Strong.");
} else {
console.log(message);
}
Also, we can combine all these regex patterns into single regex:
let regularExpression = /^(\S)(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[~`!##$%^&*()--+={}\[\]|\\:;"'<>,.?/_₹])[a-zA-Z0-9~`!##$%^&*()--+={}\[\]|\\:;"'<>,.?/_₹]{10,16}$/;
Note: The regex discussed above will check following patterns in the given input value/password:
It must not contain any whitespace.
It must contain at least one uppercase, one lowercase and one numeric character.
It must contain at least one special character. [~`!##$%^&*()--+={}[]|\:;"'<>,.?/_₹]
Length must be between 10 to 16 characters.
Thanks!

International UTF-8
None of the solutions here allows international characters, i.e. éÉáÁöÖæÆþÞóÓúÚ, but are only focused on the english alphabet.
The following regEx uses unicode, UTF-8, to recognise upper and lower case and thus, allow international characters:
// Match uppercase, lowercase, digit or #$!%*?& and make sure the length is 8 to 96 in length
const pwdFilter = /^(?=.*\p{Ll})(?=.*\p{Lu})(?=.*[\d|##$!%*?&])[\p{L}\d##$!%*?&]{8,96}$/gmu
if (!pwdFilter.test(pwd)) {
// Show error that password has to be adjusted to match criteria
}
This regEx
/^(?=.*\p{Ll})(?=.*\p{Lu})(?=.*[\d|##$!%*?&])[\p{L}\d##$!%*?&]{8,96}$/gmu
checks if an uppercase, lowercase, digit or #$!%*?& are used in the password. It also limits the length to be 8 minimum and maximum 96, the length of 😀🇮🇸🧑‍💻 emojis count as more than one character in the length.
The u in the end, tells it to use UTF-8.

After a lot of research, I was able to come up with this. This has more special characters
validatePassword(password) {
const re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!##$%^&*()+=-\?;,./{}|\":<>\[\]\\\' ~_]).{8,}/
return re.test(password);
}

it,s work perfect for me and i am sure will work for you guys checkout it easy and accurate
var regix = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*])(?=.
{8,})");
if(regix.test(password) == false ) {
$('.messageBox').html(`<div class="messageStackError">
password must be a minimum of 8 characters including number, Upper, Lower And
one special character
</div>`);
}
else
{
$('form').submit();
}

<div>
<input type="password" id="password" onkeyup="CheckPassword(this)" />
</div>
<div id="passwordValidation" style="color:red" >
</div>
function CheckPassword(inputtxt)
{
var passw= /^(?=.*\d)(?=.*[a-z])(?=.*[^a-zA-Z0-9])(?!.*\s).{7,15}$/;
if(inputtxt.value.match(passw))
{
$("#passwordValidation").html("")
return true;
}
else
{
$("#passwordValidation").html("min 8 characters which contain at least one numeric digit and a special character");
return false;
}
}

If you check the length seperately, you can do the following:
var regularExpression = /^[a-zA-Z]$/;
if (regularExpression.test(newPassword)) {
alert("password should contain atleast one number and one special character");
return false;
}

When you remake account password make sure it's 8-20 characters include numbers and special characters like ##\/* - then verify new password and re enter exact same and should solve the issues with the password verification

Here is the password validation example I hope you like it.
Password validation with Uppercase, Lowercase, special character,number and limit 8 must be required.
function validatePassword(){
var InputValue = $("#password").val();
var regex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*])(?=.{8,})");
$("#passwordText").text(`Password value:- ${InputValue}`);
if(!regex.test(InputValue)) {
$("#error").text("Invalid Password");
}
else{
$("#error").text("");
}
}
#password_Validation{
background-color:aliceblue;
padding:50px;
border:1px solid;
border-radius:5px;
}
#passwordText{
color:green;
}
#error{
color:red;
}
#password{
margin-bottom:5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="password_Validation">
<h4>Password validation with Uppercase Lowercase special character and number must be required.</h4>
<div>
<input type="password" name="password" id="password">
<button type="button" onClick="validatePassword()">Submit</button>
<div>
<br/>
<span id="passwordText"></span>
<br/>
<br/>
<span id="error"></span>
<div>

Very helpful. It will help end user to identify which char is missing/required while entering password.
Here is some improvement, ( here u could add your required special chars.)
function validatePassword(p) {
//var p = document.getElementById('newPassword').value,
const errors = [];
if (p.length < 8) {
errors.push("Your password must be at least 8 characters");
}
if (p.length > 32) {
errors.push("Your password must be at max 32 characters");
}
if (p.search(/[a-z]/) < 0) {
errors.push("Your password must contain at least one lower case letter.");
}
if (p.search(/[A-Z]/) < 0) {
errors.push("Your password must contain at least one upper case letter.");
}
if (p.search(/[0-9]/) < 0) {
errors.push("Your password must contain at least one digit.");
}
if (p.search(/[!##\$%\^&\*_]/) < 0) {
errors.push("Your password must contain at least special char from -[ ! # # $ % ^ & * _ ]");
}
if (errors.length > 0) {
console.log(errors.join("\n"));
return false;
}
return true;
}

my validation shema - uppercase, lowercase, number and special characters
new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9_])")

Related

Validating a password using JavaScript

I'm trying to make a password validation in JS to accept 8-15 digits with at least 1 lower case with this function below, however, it always returns True!
function validatepassword(){
var pass= document.getElementById("pass1").value;
var tester= /^(?=.*[\d])(?=.*[0-9])(?=.*[a-z])[\w]]{8,15}$/;
if (tester.test(pass))
{
document.getElementById("p1prompt").innerHTML=("valid " + "&#10004");
document.getElementById("p1prompt").style.color="green";
return true;
}
else {
document.getElementById("p1prompt").style.color="red";
document.getElementById("p1prompt").innerHTML=("at least 8 digits containing a lower case");
return false;
}
}
EDIT:
Special thanks to Smarx for allowing to use his answer.
function validatepassword(){
var pass= document.getElementById("pass1").value;
if (/[a-z]/.test(pass) && /\d/.test(pass) && pass.length >= 8 && pass.length <= 15)
{
document.getElementById("p1prompt").innerHTML=("valid " + "&#10004");
document.getElementById("p1prompt").style.color="green";
return true;
}
else {
document.getElementById("p1prompt").style.color="red";
document.getElementById("p1prompt").innerHTML=("at least 8 characters containing a lower case");
return false;
}
}
Password : <input type="password" id="pass1">
<p id="p1prompt"></p>
<button onclick='validatepassword()' type="button">Validate</button>
EDIT
I misread the question... I'm actually no longer sure what it's asking for. (The regular expression and the description and the error message in the code all suggest different password requirements.)
The answer below tests for "8-15 characters including at least one digit and at least one lowercase letter."
Although my comment above gives a fix to the regular expression, when you find yourself using a somewhat complicated expression, sometimes it's better to simplify your code by using multiple simpler tests instead. For example:
function isValid(password) {
return /[a-z]/.test(password) && // contains a lowercase letter
/\d/.test(password) && // contains a digit
password.length >= 8 && // at least 8 characters
password.length <= 15; // no more than 15 characters
}
But again, these restrictions are harmful for your users' security. It prevents them from using good, long, random passwords.

Password validation by using java script regular expression contains at least two digit anywhere. It can contain special characters and letters

I need to check for password by using java script regular expression. for the password check, it should have at least two digit, it can contain special character, it has letters as well.
I believe the following script should do the trick. If you're going to use this script, you'll need a button that calls the function with the inputted password as its argument. I hope this helps.
var password;
var passValid = false;
function checkPass(enteredPass) {
if(enteredPass.length >= 2) { //Makes sure that the entered password is equal to or higher than the minimum length
var numsFound = 0;
var letterFound = false;
var splitPass = enteredPass.split("");
for(i=0; i < enteredPass.length; i++) { //Checks all characters for letters and numbers
if(splitPass[i] >= 0 && splitPass[i] <= 9) {
numsFound++;
} else if(splitPass[i] >= "a" && splitPass[i] <= "z" || splitPass[i] >= "A" && splitPass[i] <= "Z") {
letterFound = true;
};
if(numsFound >= 2 && letterFound) { //Successful scenario
password = enteredPass;
console.log("the entered password is valid, updated password successfully");
return;
};
};
};
console.log("the entered password is invalid, update cancelled"); //Error scenario
};
I have framed regular expression, which should check for alphanumeric along with set of special characters and find at least 2 digits.
\(?=(?:[^0-9]*[0-9]){2,})[a-zA-Z0-9!#$*\-.\/?_&,]{1,}\
I took the help of https://regex101.com site for reference & testing.

2+ out of 4 conditions regex

I have 4 requirements for user passwords:
At least 1 a-z char
At least 1 A-Z char
At least 1 0-9 char
At least 1 symbol in .!##$%^&*()_
However, user has to fulfill only 2+ of 4 conditions.
Passwords VVVV1111, !234567, AaAaAaAa or A1!aA1!a are valid, passwords VVVVVVVV, 12345678, aaaaaaa, !!!!!!! are not.
How can I make 2 of 4 OR regexp?
I came up with this for 3 conditions (A-Z, a-z & 0-9):
^((?=.*?[A-Z])|(?=.*?[0-9]))((?=.*?[a-z])|((?=.*?[A-Z])(?=.*?[0-9]))).{8,30}$
But I think there has to be a better option because this regexp becomes really big with 4th condition.
Always break down big problems into smaller ones.
Define a separate Regex for each of your four different conditions, then check if enough of them are fulfilled.
For example:
var checks = {
lowercase: /[a-z]/,
uppercase: /[A-Z]/,
number: /[0-9]/,
symbol: /[.!##$%^&*()_]/
}, passcount = 0, results = {};
for( var k in checks) if( checks.hasOwnProperty(k)) {
if( checks[k].test(password)) {
passcount++;
results[k] = true;
}
else results[k] = false;
}
if( passcount < 2) {
alert("Your password didn't meet enough conditions.\n" +
"[Provide useful info here - 'results' object lists " +
"whether each test passed or failed, so use that for " +
"a user-friendly experience!]");
return false;
}
return true;
And finally, obligatory xkcd comic:
You can use following expression:
/[a-z]/.test(pass)+/[A-Z]/.test(pass)+/\d/.test(pass)+/[.!##$%^&*()_]/.test(pass)>2

password validation script is not working

I am using following script to validate password. Aims For validations are :
Password field should not be empty
Password Length should be between 6 and 10 characters
Password should not contain spaces and special characters
Password should be Alphanumeric.
But With following code , it passes first 3 aims but even after entering Alphanumeric text, it is till alerting:
"Password Should Contain Alphabet And Numbers Both".
Need your help
Code is :
if(document.subForm.password.value==""){
alert("Please Enter Your Desired Password....");
document.subForm.password.focus();
return false;
}
if(document.subForm.password.value.length < 6 || document.subForm.password.value.length > 10){
alert("Password Length Should Be In Between 6 And 10 Characters.");
document.subForm.password.focus();
return false;
}
var re = /^[\w\A-Z]+$/;
if(!re.test(document.subForm.password.value)) {
alert ("Your Password Has Spaces In Between The Words \n\nOr\n\nIt Contains Special Characters.\n\nThese Are Not Allowed.\n\nPlease Remove Them And Try Again.");
document.subForm.password.focus();
return false;
}
var realphanumeric = /^[a-z_A-Z_0-9]+$/;
if (!realphanumeric.test(document.subForm.password.value)){
alert("Password Should Contain Alphabet And Numbers Both");
document.subForm.password.focus();
return false;
}
Aragon0 suggested to use an open-source script from dropbox to check password strength. I recommend checking it out.
If you'd like one regular expresion to check everything:
^\w{6,10}$
Explanation:
From start (^ ) to end ($) of the string...
match only alphanumeric characters ([A-Za-z_0-9]),
with a length of 6-10 characters ({6-10})
If you want to force the user to have at least one number you can do that like this:
^(?![A-Za-z_]+$)\w{6,10}$
Your regex
/^[a-z_A-Z_0-9]+$/
doesn't do what you want. It will match the password "Test" but not "te#st".
You could use two regexes, which both need to match:
/[a-zA-Z]+/
/[0-9]+/
Btw, you should not enforce alphanumeric passwords or length constraints. You could use Dropbox's password strength script (https://github.com/dropbox/zxcvbn)
Some sample code with zxcvbn:
<script src="//cdn.jsdelivr.net/zxcvbn/1.0/zxcvbn-async.js" />
<script>
var result = zxcvbn(document.subForm.password.value);
if(result.entropy<56) // 56 is very secure, you could also lower it to 48 if you need to.
{
alert("Your password is too weak. It would be cracked " + result.crack_time_display);
return false;
}
</script>

Password - uppercase characters JavaScript

Excuse if this is a stupid question. I'm doing a web design subject at uni and am completely stuck. I have to validate a password using Javascript to ensure it has and uppsercase, lowercase, numerical character, and at least 4 characters.
This is the code I have, it's giving me alerts to say I HAVEN'T included the characters, but when I HAVE included them I'm still getting the alert. Any help appreciated.
var y = document.forms["loginDetails"]["password"].value;
if (y.length < 4) {
alert("Your password needs a minimum of four characters")
}
if (y.search[/a-z/i] < 1) {
alert("Your password needs a lower case letter")
}
if (y.search[/A-Z/i] < 1) {
alert("Your password needs an uppser case letter")
}
if (y.search[/0-9/] < 1) {
alert("Your password needs a number")
return false;
}
Your code had several errors
comparision should be <0 not <1 (search returns negative value when regexp is not found)
/i in regexp (case insensitive - not appropriate when trying to figure out upper/lower case characters)
call of search function was wrong (usage of [] instead of () )
in regexp [] was missing ([] in regexp means one character from given range, so [a-z] will match each lowercase character whereas a-z will match just string 'a-z')
It should look like:
if (y.length < 4) {
alert("Your password needs a minimum of four characters")
} else if (y.search(/[a-z]/) < 0) {
alert("Your password needs a lower case letter")
} else if(y.search(/[A-Z]/) < 0) {
alert("Your password needs an uppser case letter")
} else if (y.search(/[0-9]/) < 0) {
alert("Your password needs a number")
} else {
// Pass is OK
}
There were a few issues with your code:
String.search() returns -1 if the regular expression is not found. Checking against < 1 will still return true incorrectly if the string is found at the 0th (first) character.
String.search() is a function and needs to be called with parentheses ( ) surrounding the arguments, not brackets [ ].
You do not want to perform case-insensitive searches in your regular expressions, so remove the /i option.
Try keeping track of whether or not there was an error in another variable. Then if any of the cases generated an error, you can return false.
Try this:
var error = false;
var message = '';
if (y.length < 4) {
message += "Your password needs a minimum of four characters. ";
error = true;
}
if (y.search(/[a-z]/) == -1) {
message += "Your password needs at least one lower case letter. ";
error = true;
}
if (y.search(/[A-Z]/) == -1) {
message += "Your password needs at least one upper case letter. ";
error = true;
}
if (y.search (/[0-9]/) == -1) {
message += "Your password needs a number.";
error = true;
}
if (error) {
alert(message);
return false;
}
Note that "search" is a function, so you have to call it like y.search(), not with [] brackets (those are used to access a member. y"search" would have the same effect, but search[] is not ok, because it is not an array
Try changing your code this way by:
Adding return false; to each of the failure statement.
Changing the search() function syntax.
You don't need to use /i as it doesn't check the cases.
Code
var y = document.forms["loginDetails"]["password"].value;
if (y.length < 4) {
alert("Your password needs a minimum of four characters")
return false;
}
if (y.search(/[a-z]/) < 1) {
alert("Your password needs a lower case letter")
return false;
}
if (y.search(/[A-Z]/) < 1) {
alert("Your password needs an uppser case letter")
return false;
}
if (y.search(/[0-9]/) < 1) {
alert("Your password needs a number")
return false;
}
the main problem is that you're using the 'i' modifier, what tells the regexp to be case insensitive, try without this modifier.
To improve the user experience I use one error message, so, yo could use this code:
if(/[a-z]+/.test(s) && /[A-Z]+/.test(s) && /\d+/.test(s) && s.length >= 4)
return true;
alert("Your password needs Upper and lower case letters, numbers and a minimum four chars");
return false;
You could try this:
var y = document.forms["loginDetails"]["password"].value;
if (y.length < 4) {
alert("Password should contain minimum four characters");
return false;
}
var pwd=/^(?=.*[a-z])/;
var pwd1=/^(?=.*[A-Z])/;
var pwd2=/^(?=.*[0-9])/;
if (pwd.test(y) == false) {
alert("Password Should contain atleast One lowerCase letter");
return false;
}
if (pwd1.test(y) == false) {
alert("Password Should contain atleast One UpperCase letter");
return false;
}
if (pwd2.test(y) == false) {
alert("Password Should contain atleast One Number");
return false;
}
Or, you could do the same in a single line as well :
var pwd=/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])/;
if (pwd.test(y) == false) {
alert("Password Should contain atleast One Number, One UpperCase and a lowercase letter");
return false;
}

Categories

Resources