Match at least one letter, one number and one non-alphanum - javascript

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;
}

Related

why it is not working to validate only numbers, not going to true condition

The following function is for validating numbers.
function strictlynumber(obj)
{
var numbers=/^[0-9]+$/;
if (obj!=numbers)
{
alert("please enter numbers only");
return false;
}
return true;
}
Use regexObject.test(obj) method,
In your code obj!=numbers , is a test of equality , it will always return true.
Modified code :
function strictlynumber(obj)
{
var numbers=/^[0-9]+$/;
if (!numbers.test(obj))
{
alert("please enter numbers only");
return false;
}
return true;
}
Please follow the below link for more info on Regular Expression :
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
You have to test the value against the Regex. You can not simply compare the value passed with Regex object in that way. Try the following:
function strictlynumber(obj) {
var numbers=/^[0-9]+$/;
if (!numbers.test(obj)) {
alert("please enter numbers only");
return false;
}
return true;
}
console.log(strictlynumber(5))
Your statement obj!=numbers is comparing the regular expression /^[0-9]+$/ to obj
You need to execute the regular expression against the input such as.
function strictlynumber(obj)
{
var numbers=/^[0-9]+$/;
if (!obj.match(numbers))
{
alert("please enter numbers only");
return false;
}
return true;
}
Here we use the match method of a string prototype.

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;
}

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)+/

Javascript check for spaces

I have this function but I want to check for spaces only in the front and back, not in the middle before i sent back what can i do with it...
function validateNumeric() {
var val = document.getElementById("tbNumber").value;
var validChars = '0123456789.';
for(var i = 0; i < val.length; i++){
if(validChars.indexOf(val.charAt(i)) == -1){
alert('Please enter valid number');
return false;
}
}
return true;
}
Time for regular expressions.
function startsOrEndsWithWhitespace(str)
{
return /^\s|\s$/.test(str);
}
Tests:
> /^\s|\s$/.test('123454')
false
> /^\s|\s$/.test('123 454')
false
> /^\s|\s$/.test(' 123454')
true
> /^\s|\s$/.test(' 123454 ')
true
> /^\s|\s$/.test('123454 ')
true
if i dont wanna accept 1 1 what do i have to change
function containsWhitespace(str)
{
return /\s/.test(str);
}
Tests:
> /\s/.test('123454')
false
> /\s/.test('123 454')
true
> /\s/.test(' 123454')
true
> /\s/.test('123454 ')
true
> /\s/.test(' 123454 ')
true
> /\s/.test(' 123 454 ')
true
For a really simple solution, if you can use jQuery, use jQuery.trim() and compare the trimmed string with the original. If not equal, then there were spaces so the number is invalid.
function trim (myString)
{
return myString.replace(/^\s+/g,'').replace(/\s+$/g,'')
}
source
To trim your string you can write something like this, as it's been said before:
function trim(str){
return str.replace(/^\s+|\s+$/g), '');
}
But why bother?
Want you really want is:
function validateNumeric(str) {
return !isNaN(parseFloat(str));
}
Note your original code accepts something like "..." or "7.8..9" as being numeric, which is wrong.
Update: kennebec has called my attention to the fact that parseFloat() will ignore trailing garbage at the end of string. So I call your attention to this alternative given in an answer to question "Validate numbers in JavaScript - IsNumeric()":
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
(Original credit goes to CMS).
function validateNumeric() {
var val = document.getElementById("tbNumber").value;
if (!/^\s*(?:\d+(?:\.\d*)?|\.\d+)\s*$/.test(val)) {
alert('Please enter a valid number');
return false;
}
return true;
}
(?:\d+(?:\.\d*)|\.\d+) breaks down as follows:
\d+ is any number of digits, e.g. 123
(\.\d*)? optionally matches a fraction, e.g. .25 and . or blank but not .1.2
\.\d+ matches a fraction without an integer part as in .5 but not 1.5.
(?:abc|def) groups things together and matches either abc or def
/^\s*(?:\d+(?:\.\d*)|\.\d+)\s*$/ means any number of spaces followed by one or more decimal digits followed by any number of spaces. So it does what your validChars loop did plus allows spaces at the start and end.

Categories

Resources