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.
I am making a login form. Before it submits, I check if all the fields are filled in. I also check if the password is longer than 7 characters and contains at least one number, at least one character, and no spaces. My current code keeps on telling me that I am missing a character no matter what I enter. This is the code:
if($("#password").val()==""){
error += "The password is required.<br>";
}
else if($("#password").val().length<8){
error += "Your password needs at least 8 characters.<br>";
}
else if($("#password").val().length >= 8){
var pass = $("#password").val().split("");
var hasNum = false;
var hasChar = false;
var hasSpace = false;
for(var i = 0; i < pass.length; i++){
if(pass[i] == " "){
hasSpace = true;
}
else if(Number(pass[i]) == NaN){
hasChar = true;
}
else if(Number(pass[i]) != NaN){
hasNum = true;
}
}
if(!hasChar){
error += "Your password must contain at least one character.<br>";
}
if(!hasNum){
error += "Your password must contain at least one number.<br>";
}
if(hasSpace){
error += "Spaces are not allowed in a password.<br>";
}
}
I first check for a space. Then I check if a character can be converted to a number. If not, then it must be a string. If it can be converted, it must be a number. Whatever I type in, it always says "Your password must contain at least one character". How can I fix this? I will give you more code if it is necessary.
The problem is that NaN compares unequal (via ==, !=, ===, and !==) to any other value, including to another NaN value:
NaN === NaN;// false
Number('S') == NaN; //false
Number(10) == NaN; //false
try to use isNaN() instead.
I have been trying to make a password validator. It only allows passwords with at least one letter, at least one number and at least one non-alphanumeric character.
I have the below which works:
function passwordValidate(password, password_c, msg)
{
if (notEmpty(password, "Enter a password"))
{
if (password.value === password_c.value)
{
if(/\W/.test(password.value))
{
if (/\d/.test(password.value) && /[a-zA-Z]/.test(password.value))
{
return true;
} else {
alert(msg);
}
} else {
alert("Must have a special character in your password");
}
} else {
alert("Passwords don't match");
}
}
return false;
}
I initially had "password.value.match("\W|_")" which was causing a problem so changed it to "/\W/.test(password.value)". Does anyone know how I can combine this into one regular expression?
You could use assertions.
The assertions sub-pattern is matched in the regular manner except that it doesnt cause the current matching position to be changed.
Try:
var rgx=/(?=.*\d)(?=.*[a-zA-Z])(?=.*[^0-9a-zA-Z])/
//my test
var theTest=['azert7ui#i4','uiou5','4761238|z','jhkj','8989go','457#457'];
for (i=0;i<theTest.length;i++) alert(theTest[i]+' '+rgx.test(theTest[i]));
So initially we test 1 digit (?=.*\d) . It can be preceded with something or not.
Next is alphabetic characters and non-alphabetic characters. The use of \w ("word" character is any letter or digit) which duplicate digit is wrong (test is true with only digits and special characters).
The \ is a special meaning in a string so the test is wrong.
Hope that helps
Also, instead of making these nested staircases of if statements, break out early. It's much cleaner:
function passwordValidate(password, password_c, msg) {
if (!notEmpty(password, "Enter a password")) {
return false;
}
if (password.value !== password_c.value) {
alert("Passwords don't match");
return false;
}
if(!/(?=.*\d)(?=.*[a-zA-Z])(?=.*[^\da-zA-Z])/.test(password.value)) {
alert("Must have a special character in your password");
return false;
}
alert(msg);
return true;
}
// It may be easier to do separate tests-
function testPassword(pw){
pw= pw.replace(/\s+/, ''); //remove spaces
var msg= [' non-alphanumerical', ' alphabetical', ' digit'],
rx= [/\W/,/[a-zA-Z]/,/\d/];
for(var i= 0;i<3;i++){
if(!rx[i].test(pw)) throw Error('At least one'+
msg[i]+' character is required');
}
return pw;
}
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_])")
I have one input field. It may contain either a name or a number.
If the input has at least one letter we handle it as name and its length should be 11 or lower. So valid input might be Bob, 12Bob or Bob23. No empty spaces or other chars are allowed so Bob_1, Bob 23 would be invalid.
If the input contains just digits we handle it as number, if so the number musts start with 00 and should be 16 in length or lower.
Here is my code:
function validateName(){
var name = $('#absender').val();
var length = name.length;
if(/^[a-zA-Z0-9]+$/.test(name)){
if(length > 11){
$('#absender').addClass('error');
$('#bsenderInfo').addClass('error');
disableSave();
return false;
}else{
$('#absender').removeClass('error');
$('#absenderInfo').removeClass('error');
enableSave();
return true;
}
}else if(/^[0-9]+$/.test(name)){
if(name.substring(0,2) != "00"){
$('#absender').addClass('error');
$('#bsenderInfo').addClass('error');
disableSave();
return false;
}
if(length > 17){
$('#absender').addClass('error');
$('#bsenderInfo').addClass('error');
disableSave();
return false;
}else{
$('#absender').removeClass('error');
$('#absenderInfo').removeClass('error');
enableSave();
return true;
}
}else{
$('#absender').addClass('error');
$('#bsenderInfo').addClass('error');
disableSave();
return false;
}
}
Does not matter what the input is, it gives me false if length is 12. Any ideas?
It's because of this line:
if(/^[a-zA-Z0-9]+$/.test(name)){
Every number string fits this regex well, so the "else" statement will be never executed.
You can correct this by checking the number-username case before checking the case [a-zA-Z0-9].
A single regex can handle it:
if (/^(00[0-9]{1,14}|[a-z0-9]{,11})$/i.test(name)) {
// Success condition
...
} else {
// Failure condition
...
}