I am trying to build a regex that matches for the following
6 letters
digits
1 punctuation
my special characters from my backend to support js special_characters = "[~\!##\$%\^&\*\(\)_\+{}\":;,'\[\]]"
and a minimum of a length of at least 8 or longer.
my password javascript client-side is the following, but however, how can I build a regex with the following data?
if (password === '') {
addErrorTo('password', data['message']['password1']);
} else if(password){
addErrorTo('password', data['message']['password1']);
}else {
removeErrorFrom('password');
}
First check if password.length >= 6
Then I would do it like this:
Set up a letterCount, numCount, puncCount
Loop through the string and earch time you encounter a letter, increase the letterCount (letterCount++), each time you encounter a number increase numCount and so on.
Then validate your password using the counter variables.
This is a good approach because you can tell the user what went wrong. For example, if they only entered 1 number, you can see that from the numCount and tell them specifically that they need at least 2 numbers. You can't do that with just one Regex.
EDIT: Heres the code:
for (let i = 0; i < password.length; i++) {
const currentChar = password[i];
if (checkIfLetter(currentChar)) {
letterCount++;
}
if (checkIfNumber(currentChar)) {
numCount++;
}
if (checkIfPunc(currentChar)) {
puncCount++;
}
}
Then check if the numCount > 2 and so on. I would write the actual regexs but I don't know them myself. It should be pretty easy, just return true if the provided char is a letter for the first function, a number for the second one and so on.
You can use multiple REGEXes to check for each requirement.
let containsAtLeastSixChars = /(\w[^\w]*){6}/.test(password);
let containsAtLeastTwoDigits = /(\d[^\d]*){2}/.test(password);
let containsAtLeastOnePunct = new RegExp(special_characters).test(password);
let isAtLeast8Digits = password.length >= 8;
Then if any of these booleans are false, you can inform the user. A well designed site will show which one is wrong, and display what the user needs to fix.
^(?=.*[0-9]).{2}(?=.*[a-zA-Z]).{6}(?=.*[!##$%^&*(),.?":{}|<>]).{1}$
6Letters, 2digits, and 1 special character.
Related
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 " + "✔");
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 " + "✔");
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 am trying to validate min 1 and max 59 with the following regexp but not working as expected.
^[1-5]?[1-9]$
What is wrong with the expression?
It's work: ^([1-5][0-9]|[1-9])$ (#Tushar)
if (/^([1-5][0-9]|[1-9])$/.test(number)) {
// Successful match
} else {
// Match attempt failed
}
The better/faster way (without regex):
function validate(number) {
number = parseInt(number);
return number > 0 && number < 60;
}
for (var i = 0; i < 65; i++) {
console.log(validate(i));
}
Tested:
Everyone busy trying to provide a solution missed the real question OP asked.
What is wrong with the expression?
Well here is your regex: ^[1-5]?[1-9]$
What you are trying to do is match a number having first digit (optional) in range 1 to 5 and second digit in range 1-9. And since you want to match number from 1 to 59, you will be missing is numbers like 10,20,30,40,50 as pointed out in one comment.
I've been doing a lot of searching, chopping and changing, but I'm...slightly lost, especially with regards to many of the regex examples I've been seeing.
This is what I want to do:
I have a text input field, size 32.
I want users to enter their telephone numbers in it, but I want them to enter a minimum of 10 numbers, separated by a single comma. Example:
E.g. 1
0123456789,0123456789 = right (first group is >=10 numbers, second group = >=10 numbers & groups are separated by a single comma, no spaces or other symbols)
E.g. 2
0123456789,,0123456789 = wrong (because there are 2 commas)
E.g. 3
0123456789,0123456789,0123456789 = right (same concept as E.g. 1, but with 3 groups)
I've got the following, but it does not limit the comma to 1 per 10 numbers, and it does not impose a minimum character count on the number group.
$(document).ready(function(){
$("#lastname").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && String.fromCharCode(e.which) != ','
&& (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
Preferably, I'd like to warn the user of where they are going wrong as well. For example, if they try to enter two commas, I'd like to specifically point that out in the error, or if they havent inserted enough numbers, i'd like to specifically point that out in the error. I'd also like to point out in the error when neither a number or a comma is inserted. I'd like to ensure that the tab, and F5 keys are not disabled on the keyboard as well. And very importantly, I'd like to specifically detect when the plus or addition key is used, and give a different error there. I think I'm asking for something a little complex and uninviting so sorry :/
The example code I provided above works pretty well across all browsers, but it doesn't have any of the minimum or maximum limits on anything I've alluded to above.
Any help would be appreciated.
As far as a regex that will check that the input is valid (1-3 phone numbers of exactly 10 digits, separated by single commas), you can do this:
^\d{10}(,\d{10}){0,2}$
Try like the below snippet without Regex
var errrorMessage = '';
function validateLength (no) {
if(!no.length == 10) {
return false;
}
return true;
}
function validatePhoneNumbers (currentString, splitBy) {
if(currentString) {
var isValid = true,
currentList = currentString.split(splitBy);
// If there is only one email / some other separated strings, Trim and Return.
if(currentList.length == 1) {
errrorMessage = 'Invalid Length in Item: 1';
if(validateLength( currentString.trim() )) isValid = false;
}
else if(currentList.length > 1) {
// Iterating mainly to trim and validate.
for (var i = 0; i < currentList.length; i++) {
var listItem = currentList[i].trim();
if( validateLength(listItem ) ) {
isValid = false;
errrorMessage = 'Invalid Length in Item:' + i
break;
}
// else if for some other validation.
}
}
}
return isValid;
}
validatePhoneNumbers( $("#lastname").val() );
Thanks for your help with my earlier question:
How to find all instances and display in alert
Now I discover that I need to include some invalid character validation.
I'm trying to figure out how to include a set of regex invalid characters as part of the validation that will also show up in the same alert/textbox/whatever as the "too long/too short" validation.
So, I have a textbox which users will type or paste comma separated values such as AAAAAAA,BBBBBBB,CCCCCCCC,DDDDDDDD
And they cannot be more or less than seven characters long and they can only include certain characters.
I currently have have two separate pieces of Javascript that I'm trying to now combine:
var Invalidchars = "1234567890!##$%^&*()+=[]\\\';./{}|\":<>?";
for (var i = 0; i < document.getElementById("TextBox1").value.length; i++) {
if (Invalidchars.indexOf(document.getElementById("TextBox").value.charAt(i)) != -1){
alert
and this
var val = document.getElementById("Textbox1").value,
err = $.grep(val.split(','), function(a) { return a.length != 7; });
if (err.length) {
alert("All entries must be seven (7) characters in length. Please correct the following entries: \n" + err);
return false;
}
return true;
Any help is much appreciated!
=================================================
SOLUTION
Took a while, but using Tenub's code (which didn't quite combine my two sets code, but was close enough), I finally figured out how to merge my two sets of code into one. Here's the code if anyone is ever interested in using it:
var val = document.getElementById("TextBox1").value,
err = $.grep(val.split(','), function(a) {return (a.length = (!/^[^0-9!##$%^&*()+=;.\/\{}|:<>\\?\[\]\'\"]{7}$/.test(a)));});
if (err.length){
document.getElementById("DIV1").style.display = "inline-block";
document.getElementById("TextBox2").value = err.join(',');
return callback (false);
}
document.getElementById("DIV1").style.display = "none";
return true;
The answer is as simple as it is elegant:
var val = document.getElementById("Textbox1").value;
if(!/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test(val)) {
// handle invalid value
}
This tests that the string is 7 characters in length and does not contain any character within the brackets after the "^" (also some characters are escaped with a "\").
You can test in console:
/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test('adfFDKZ'); // returns true
/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test('adf(DKZ'); // returns false
Try this:
/*
* This regex matches all the invalid characters. I escaped the
* special characters.
*/
var regex = /.*[0-9!##\$%\^&\*\(\)\+=\[\]\\';\./\{\}\|":\<\>\?]+.*/;
var text = document.getElementById("TextBox1").value;
/* Test for match...much faster than a for-loop under any circumstances */
if (text.matches(regex)) {
alert("Invalid characters present. Please correct the input");
return false;
}
/* split on delimiter */
var err = $.grep(val.split(','), function(a) { return a.length != 7; });
if (err.length) {
alert("All entries must be seven (7) characters in length. Please correct the following entries: \n" + err);
return false;
}
Please tell me if there are any bugs in this. Also, the only real way to test for this in one step is to set up an enormously long regex. Also, with only one check, it would make it a little harder to guide the user to make the right correction. I will mention that.
Either I'm being really retarded here or its just the lack of sleep but why doesn't this work? If I use the "or" operator it works for each separate test but as soon as it change it to the "and" operator it stops working.
I'm trying to test the password input of a form to see if its contains lowercase, uppercase and at least 1 number of symbol. I'm having a lot of trouble with this so help would be lovely, here is the code I have.
var upperCase= new RegExp('[^A-Z]');
var lowerCase= new RegExp('[^a-z]');
var numbers = new RegExp('[^0-9]');
if(!$(this).val().match(upperCase) && !$(this).val().match(lowerCase) && !$(this).val().match(numbers))
{
$("#passwordErrorMsg").html("Your password must be between 6 and 20 characters. It must contain a mixture of upper and lower case letters, and at least one number or symbol.");
}
else
{
$("#passwordErrorMsg").html("OK")
}
All of your regular expressions are searching for anything except the ranges that you have provided. So, [^A-Z] looks for anything but A-Z.
You are also negating each match.
You might try modifying your regular expression definitions by removing the ^, and then reversing your logic. So,
var upperCase= new RegExp('[A-Z]');
var lowerCase= new RegExp('[a-z]');
var numbers = new RegExp('[0-9]');
if($(this).val().match(upperCase) && $(this).val().match(lowerCase) && $(this).val().match(numbers))
{
$("#passwordErrorMsg").html("OK")
}
else
{
$("#passwordErrorMsg").html("Your password must be between 6 and 20 characters. It must contain a mixture of upper and lower case letters, and at least one number or symbol.");
}
This might even be a bit more intuitive to read?
var upperCase= new RegExp('[A-Z]');
var lowerCase= new RegExp('[a-z]');
var numbers = new RegExp('[0-9]');
if($(this).val().match(upperCase) && $(this).val().match(lowerCase) && $(this).val().match(numbers) && $(this).val().lenght>=6 && $(this).val()<=20)
{
$("#passwordErrorMsg").html("OK")
}
else
{
$("#passwordErrorMsg").html("Your password must be between 6 and 20 characters. It must contain a mixture of upper and lower case letters, and at least one number or symbol.");
}