password validation script is not working - javascript

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>

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.

I need help in javascript password validation?

I am working on a password validation script.
The following code is working fine with numbers, upper- and lower-case letters.
The only problem in .press the spacebar key, length is more than 8,
display return true.
not allowed to only special characters.
$("#password").keyup(function () {
var validated = true;
if (this.value.length < 8)
validated = false;
if (!/\d/.test(this.value))
validated = false;
if (!/[a-z]/.test(this.value))
validated = false;
if (!/[A-Z]/.test(this.value))
validated = false;
if (!/[##$%\&^\-\+=!*.?~]/.test(this.value))
validated = false;
if (/[^0-9a-zA-Z##$%^&+=!*,.?~]/.test(this.value))
validated = false;
$('#password_strength').text(validated ? "Good" : "Too Weak");
When checking for symbols in your password using regex, you'll want to escape them so they're taken as the literal character, not the regex meaning of the character. For more information, I would recommend checking out:
http://www.javascriptkit.com/javatutors/redev2.shtml
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions

Regular expression to verify zip code and checking for invalid characters

I am trying to validate an input for zip codes, now this zip code should work for US, CANADA, UK, all the countries but omit any special characters, so i tried, checking for invalid characters first if that passes then i check for the zip code to either be US or if not just to make sure there are valid characters and not more than 8 (space in between them is ok as long as its now US(which includes - for 5 + 4)
The problem I am having is that 11215 for example is returning as false for the valid character validation and 11215## is returning false also.
Here are my regex:
var reg1 = /^[\^$%#!#&\*:<>\?\/\\~\{\}\(\)\+|]+$/;
var reg2 = /(^\d{5}$)|(^\d{5}-\d{4}$)|(([a-z0-9]{8})*$)/
var isOk = reg1.test("11215"); // returns false!
if(isOk)
{
isOk = isOk && reg2.test("11215");
}
var isOk2 = reg1.test("11215##"); // returns false also!
if(isOk2)
{
isOk2 = isOk2 && reg2.test("11215##");
}
The test for "bad chars", reg1 will always be false unless your string is made entirely of "bad chars". I don't think this is the behaviour you wanted.
var matchBad = /[^\s\da-z\-]/i;
// Match all non-whitespace, non-digit, non-alpabet, non-hyphen
if (false === matchBad.test("11215")) { // no bad chars detected
console.log('pass!');
// continue checking validity..
} else { // bad chars detected
console.log('fail!);
}
Your first regex is testing whether the entire string has those characters. If you want containment, remove the ^ and $ denoting the beginning and ending of your regex:
var reg1 = /[\^$%#!#&\*:<>\?\/\\~\{\}\(\)\+|]/;
This may be only part of the problem but it should get you somewhere. Note I also removed the + since it really only needs to match one character to detect a bad character.
Also another note of design. Your regex that exactly matches the pattern should really be sufficient for testing this. I'm not quite familiar though with the third type of zip, but you might want to make it capture the entire string (with ^ and $)
Javascript should be like below
<script type="text/javascript">
function IsValidZipCode(zipcode) {
var isValid = /^[0-9]{5}(?:-[0-9]{4})?$/.test(zipcode);
if (!isValid){
alert('Invalid ZipCode');
document.getElementById("zipcode").value = "";
}
}
</script>
Zipcode text should be
<input id="zipcode" class="zipcode" type="text" placeholder="Your Zipcode?" name="zipcode" onchange="IsValidZipCode(this.form.zipcode.value)" required >

Javascript regular expression password validation having special characters

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_])")

Validating textbox entry through javascript

I wanted to allow only characters in a textbox and space in between two characters.I am trying to avoid any unwanted characters and blank string in following Javascript code.
var filter = "^[a-zA-Z''-'\s]{1,40}$";
var label = $('#<%= txtName.ClientID %>').val();
if ((label.length > 0) && (label!= '')) {
if (label.match(/^[a-zA-Z \s]{1,40}$/)) {
if (label.match(/^\s$/)) {
alert("Please Enter a Valid name");
return false;
}
else {
$("#myModal").dialog('open');
}
}
else {
alert("Please Enter a Valid name");
}
}
else {
alert("Please Enter a Valid name");
}
This is working fine for everything except when user enters more than 1 space in the textbox. I was thinking that label.match(/^\s$/)) will take care of blank string or blank spaces.
Thanks
It looks like this is a job for 0 or more (the RegEx *)! (Pardon the exclamation, I'm feeling epic this morning)
/^\s$/ means "contains only one space"
I believe you are looking for
/^\s*$/ means "contains only zero or more spaces"
you should use + sign in regular expression for more than one entities.suppose if you want multiple spaces then use like var expr=/(\s)+/

Categories

Resources