I'm trying to implement password validation using regex or javascript.
unfortunately i'm a total newbie to Regex :/
the criteria are :
minimum length: 8 characters (can be upper or lower case)
must contain 1 special character (something like !?$%&#)
must contain at least one number
i found the following snippet but it's missing checking for at least character of type special+number ..
function validPassword(password) {
var has_letters = (/[a-zA-Z]/).test(password);
var has_numbers = (/[0-9]/).test(password);
var has_length = 3 <= password.length && password.length <= 30;
return has_letters && has_numbers && has_length;
}
thanks
You can use below regex to validate your password:
var regex = "^(?=.*[A-Za-z])(?=.*\d)(?=.*[$#$!%*#?&])[A-Za-z\d$#$!%*#?&]{8,}$";
This will check validation for Minimum 8 characters at least 1 Alphabet, 1 Number and 1 Special Character.
Another way would be
function validPassword(password) {
return password.length > 8
&& password.match( /[\d]/ )
&& password.split( /[\W]/ ).length == 2 ;
}
password.length > 8 checks the length should be minimum 8
password.match( /[\d]/ ) checks if it has at least one number
password.split( /[\W]/ ).length == 2 checks if it has one special character
Your regex should be like this:
(?=^.{8,}$)(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^A-Za-z0-9]).*
Here is the detail:
(?=^.{6,}$) - String is > 5 chars
(?=.*[0-9]) - Contains a digit
(?=.*[A-Z]) - Contains an uppercase letter
(?=.*[a-z]) - Contains a lowercase letter
(?=.*[^A-Za-z0-9]) - A character not being alphanumeric.
Add one extra check:
function validPassword(password) {
var has_letters = /[a-zA-Z]/.test(password);
var has_numbers = /\d/.test(password);
var has_special = /[!?$%&#]/.test(password);
var has_length = (password.length >=8 && password.length <= 30);
return has_letters && has_numbers && has_special && has_length;
}
However if you want a single regex to do all this then use lookaheads:
var re = /^(?=.*\d)(?=.*[!?$%&#])(?=.*?[a-zA-Z]).{8,30}$/;
var isValid = re.test(password);
Related
I'm trying to do a continuous validation on a string that contain a single special character also in the middle. Continuous validation means that even the partial string should return true.
By taking an example of a string like [four digits][a hyphen][three alphanumeric]
Cases
1) 1 Should validate
2) 432 Should validate
3) 1234- should validate
4) 1q21- Should not validate
5) 4532-a3s should validate
6) 8023-as12 should not validate
the regex i have now is
/^([0-9]{1,4})?\-([a-zA-Z0-9]{1,3})?$/;
This does not validate case 1 and 2 from the above listing
It does validate case 3, 4, 5, 6 from above cases
You can try
^(\d{1,3}|\d{4}(-[a-z0-9]{0,3})?)$
Regex Demo (explanation included)
I would use simple javascript to solve this problem. You loop through each character, check to see in which index range they fall in and apply validation there accordingly.
function validateString(str){
if(str.length > 8 || str.length == 0) return false;
for(var i=0;i<str.length;++i){
if(i < 4){
if(!(str.charAt(i) >= '0' && str.charAt(i) <= '9')) return false;
}else if(i == 4){
if(str.charAt(i) != '-') return false;
}else{
if(!(str.charAt(i) >= '0' && str.charAt(i) <= '9' || str.charAt(i) >= 'a' && str.charAt(i) <= 'z' || str.charAt(i) >= 'A' && str.charAt(i) <= 'Z')) return false;
}
}
return true;
}
const tests = [
'1',
'432',
'1234-',
'1q21-',
'4532-a3s',
'8023-as12',
'1-2a',
'1234ab',
'1-a',
'5555555555555',
'5555qqq',
'1234-###'
];
tests.forEach((value) => {
console.log(value + " => " + validateString(value));
});
You could make the first group not optional followed by an optional hyphen and make the group non capturing if you don't need it. If you want to match only digits as well, you could use an alternation.
^(?:\d+|[0-9]{4}-?(?:[a-zA-Z0-9]{1,3})?)$
^ Start of string
(?: Non capturing group
\d+ Match 1+ digits
| Or
[0-9]{4}-? Match 4 digits with optional -
(?: Non capture group
[a-zA-Z0-9]{1,3} Match any of the listed in the character class 1 - 3 times
)? Close group and make it optional
) Close non capturing group
$ End of string
Regex demo
If there are no more than 4 digits are allowed and the hyphen should be there in the second part you could also use:
^(?:\d{1,4}(?:-[a-zA-Z0-9]{0,3})?|\d{4})$
Regex demo
It's not something regex is particularly good at, but...
^(?:\d{1,3}|\d{4}(?:-([a-zA-Z0-9]{0,3}))?)$
You have to incrementally build parts, with satisfied parts being fully stated and mandatory, and unsatisfied parts at the end optional.
Some trick could be to have a regex only for the complete version, say:
/^\d{4}-[a-zA-Z0-9]{1,3}$/
Have a full correct pattern:
"1234-aA0"
And fulfill user input with the correct pattern before regex check:
const detect = function (userInput) {
if (userInput.length > 8) return false
const regex = /^\d{4}-[a-zA-Z0-9]{1,3}$/
const pattern = "1234-aA0"
return regex.test(userInput + pattern.slice(userInput.length))
}
const tests = ['1', '432', '1234-', '1q21-', '4532-a3s', '8023-as12', '1-2a', '1234ab', '1-a', '5555555555555', '5555qqq', '1234-###']
tests.forEach((value) => {
console.log(value + " => " + detect(value));
});
I'm trying to solve a password checker challenge and I've got to a stage where 1 string is matching for two expressions.
Rules:
return 'too short' for any string that is less than 6 characters
return 'okay' if the string is less than 12 characters, features one or more underscores, or a number, or with a mix of uppercase/lowercase letters
var str = 'aBB33'
var lessthansixRegex = new RegExp(/^(?=.*?[a-z])(?=.*?[A-Z])|(?=.*?\d{1}){0,6}$/);
var okayRegex = new RegExp(/(?=.*?[a-z])(?=.*?[A-Z])|(?=.*?\d{1})|(?=.*?[_]{1})/);
if (okayRegex.test(str) && str.length < 12) {
return 'okay';
} else if (tooshortRegex.test(str) && str.length < 6) {
return 'too short';
}
Is there a way to check this or are the paramaters of the challenge messed up.
One solution you might easily spot is the lack of '' however the 'okay' regex must have that parameter as an or '|' because there are other strings than need to match it that also don't include ''.
Feel free to let me know if you spot any other bugs.
Thanks a lot!
I think you've overcomplicated things here, why not just check the string lengths rather than write a regex for it? Also I think your regex could be simpler:
var str = 'aBB33';
var okayRegex = /[_\d]|[A-Z]+.*[a-z]+|[a-z]+.*[A-Z]+/;
if (str.length < 6 || str.length > 11) {
return 'password must be between 6 & 11 characters';
} else if (okayRegex.test(str)) {
return 'ok';
} else {
return 'invalid password';
}
Seeing as this is about the regex let me explain what's happening:
[_\d] // match any underscore or digit (number)
| // or (checks whether what's before or after is true)
[A-Z]+.*[a-z]+ // check for at least one A-Z followed by any gap
// of characters followed by at least one a-z
| // or
[a-z]+.*[A-Z]+ // reverse of last check (lower then upper)
Hope that helps!
Your regex seems too complicated. You can reach your solution by testing against each individual regex and provide a specific error message based on each condition by doing something like this
var containsNumber = new RegExp('\d');
var containsUnderscore = new RegExp('[_]');
var containsUpperCase = new RegExp('[A-Z]');
var containslowerCase = new RegExp('[a-z]');
if (str.length < 6 || str.length > 11) {
return 'password must be between 6 & 11 characters';
} else if (!containsNumber.test(str)) {
return 'password must contain a number';
}else if (!containsUnderscore.test(str)) {
return 'password must contain underscore';
}else if (!containsUpperCase.test(str)) {
return 'password must contain upper case character';
}else if (!containslowerCase.test(str)) {
return 'password must contain lower case character';
}
I need to validate a input field which should contain at least x number of numeric characters.
eg: let say I need to input value has at least 5 numeric characters
12345 - valid
AB12345 - valid
123456 - valid
AB312312 - valid
asd - not valid
213 - not valid
First I tried with input.length, but I don't know it will have a leading letters or not, so length doesn't help for me
how should I do this validation with jquery or javascript ?
Let say you are looking at validating 5 numeric then you can use regular expression /(?=(?:[\d]){5}).
What this expression does is that;
(?=) means start looking ahead
(?:[\d]) means match digits but don't capture them
{5} means (?:[\d]) (match digit) do 5 times
"use strict";
let numbers = [ '12345', 'ABC12345', '123456', 'AB312312', 'asd', '213'];
numbers.forEach(number=> {
if (/(?=(?:[\d]){5})/.exec(number)) {
console.log(number + " is valid.");
};
});
Using regular expressions will do the trick
function check(str,x){
var pattern = '^[a-zA-Z0-9]*[0-9]{'+x+'}[a-zA-Z0-9]*$';
if(str.match(pattern)) return true;
return false;
}
How about something like this
x = 5;
myString = "AB12345";
if (myString.replace(/[^0-9]/g,"").length >= x) {
alert('valid');
} else {
alert('not valid');
}
see this jsfiddle.
If
inputValue.replace(/[^0-9]/g,"").length < 5
then input field is invalid.
Here's what I tried...
It works if I only check if the value of the input is lesser than 8, but doesn't work to check if it contains at least 1 letter and 1 digit. What am I doing wrong ? =/
$(document).ready(function() {
var jVal = {
'passWord' : function() {
$('body').append('<div id="nameInfo" class="info"></div>');
var nameInfo = $('#nameInfo');
var ele = $('#password');
var pos = ele.offset();
ra = /^[A-Za-z]+$/;
re = /^[0-9]+$/;
nameInfo.css({
top: pos.top - 3,
left: pos.left + ele.width() + 15
});
if (ele.val().length < 8 & re.test(ele.value) & ra.test(ele.value)) {
jVal.errors = true;
nameInfo.removeClass('correct').addClass('error').html('← too short').show();
ele.removeClass('normal').addClass('wrong');
}
else {
nameInfo.removeClass('error').addClass('correct').html('√').show();
ele.removeClass('wrong').addClass('normal');
}
}
}
$('#password').change(jVal.passWord);
});
ra checks if the password is made ENTIRELY of letters. re checks if the password is made ENTIRELY of numbers. They are mutually exclusive and therefore cannot both be true.
Instead, use ra = /[a-z]/i; re = /[0-9]/;.
EDIT: Also, since you're using jQuery, you should be testing on ele.val(), not ele.value.
You could use a single regex to do everything:
/^(?=.*\d.*)(?=.*[a-z].*)\w{8,}$/i
The first two pieces check for both a digit, and an a-z char in the whole string, and then the last piece ensures it's at least 8 characters. You could change the last \w to . to allow special chars if so desired.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript percentage validation
I want to allow 0.00 to 100.00 only.
function ValidateText(i)
{
if(i.value.length>0)
{
i.value = i.value.replace(/[^\d.d]+/g, '');
}
}
<asp:textbox id="txtrate" runat="server" Width="200px" onkeyup= "javascript:ValidateText(this)"></asp:textbox>
It allows 0-9.0-9. Help me please. Thanks
Now this is some popular question!
This should do:
function validate(s) {
return s.match(/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/) != null;
}
var test = [
'3.0',
'5',
'99.99',
'100',
'100.00',
'100.01',
'101',
'0.3',
'.5',
'0.567',
];
for (i=0; i<test.length; ++i) {
WScript.StdOut.WriteLine(test[i] + ' => ' + validate(test[i]));
}
Outputs:
3.0 => true
5 => true
99.99 => true
100 => true
100.00 => true
100.01 => false
101 => false
0.3 => true
.5 => false
0.567 => false
Edit: the regexp can be shortened a bit without changing its meaning, credits to 6502
/^(100(\.00?)?|[1-9]?\d(\.\d\d?)?)$/
This expression should allow only what you are asking for
/^[1-9]?\d(\.\d\d?)?|100(\.00?)?)$/
Meaning is
^ start of string
( start of sub-expression ("or" between two possibilities)
[1-9]? an optional non-zero digit
\d followed by a digit
(\.\d\d?)? optionally followed with a dot and one or two digits
| or
100 the string "100"
(\.00?)? optionally followed by a dot and one or two zeros
) end of sub-expression
$ end of string
Try this one
^(?:\d{1,2}(?:\.\d{1,2})?|100(?:\.0?0)?)$
See it here on Regexr
(?:) are non capturing groups, that means the match from this group is not stored in to a variable.
\d{1,2} matches 1 or 2 digits
(?:\.\d{1,2})? This is optional, a . followed by 1 or two digits
or
100(?:\.0?0)?) matches 100 optionally followed by 1 or 2 0
^ matches the start of the string
$ matches the end of the string
Those two anchors are needed, otherwise it will also match if there is stuff before or after a valid number.
Update:
I don't know, but if you want to disallow leading zeros and numbers without two digits in the fraction part, then try this:
^(?!0\d)(?:\d{1,2}(?:\.\d{2})|100\.00)$
I removed the optional parts, so it needs to have a dot and two digits after it.
(?!0\d) is a negative lookahead that ensures that the number does not start with a 0 and directly a digit following.
How about:
var x = '76', // (i.value)
testx = Number(x.match(/\d+/)[0]);
console.log(testx>=0 && testx<=100);
Applied in your function:
function ValidateText(i) {
var val = i.value;
if (val.length>0) {
var test = Number(val.match(/\d+/)[0]);
return test >=0 && test <= 100;
}
return false;
}
Use this regex: ^(?:100(?:\.0{1,2})?|[0-9]{1,2}(?:\.[0-9]{1,2})?)$
Use this:
function ValidateText(i)
{
if(i.value.length>0)
{
i.value = i.value.match(/[1?\d{1,2}\.\d\d]/)[0];
}
}
instead of replacing all that is not (0.00 - 100.00) (as it seems to me you are trying to do), I match the allowed strings and replace the original variable content with only the matched string.
Keep in mind that this will work if you only have 1 match. If you have more, you have to trick a bit the expression and decide how to concatenate the array of results.
I don't actually see this as primarily a regex problem. I'd probably write this, particularly if you want informative error messages out it:
HTML:
<input id="percentValue" type="text" size="20">
<input type="button" value="Check" onclick="checkPercent()">
Javascript:
function checkPercent() {
var o = document.getElementById("percentValue");
var val = o.value;
if (val.length == 0) {
alert("Empty value");
return;
}
var index = val.search(/[^0-9\.]/);
if (index != -1) {
o.selectionStart = o.selectionEnd = index;
alert("Invalid characters");
return;
}
if (val.match(/\./g).length > 1)
{
alert("Number must be of the form n.n");
return;
}
var floatVal = parseFloat(val);
if (floatVal < 0 || floatVal > 100)
{
alert("Value must be between 0.00 and 100.00");
return;
}
alert("Valid value of: " + floatVal.toFixed(2));
}
jsfiddle here: http://jsfiddle.net/jfriend00/rDbAp/