I'm looking into using a jQuery password strength indicator and have found one that looks suitable.
It increases the password strength score if special characters are detected:
if (password.match(/(.*[!,#,#,$,%,^,&,*,?,_,~].*[!,#,#,$,%,^,&,*,?,_,~])/)){ score += 5 ;}
However I'd like to be able to specify additional special characters and because these lists of special characters are used in several places, I'd like to only specify the list once:
list = array(!,#,#,$,%,^,&,*,?,_,~,[,],{,},(,));
if (password.match(/(.*[list].*[list])/)){ score += 5 ;}
Is this possible?
You can use strings:
var special = "!##$%^&*?_~[]{}()".split('').join('\\');
if (password.match(new RegExp("(.*[" + special + "].*[" + special + "])")))...
(The join-with-backslashes escapes the special characters so they are treated literally by the regex engine.)
Yes, if you use the RegExp() constructor, you can pass in a string as regexp.
var list = ['\\!', '\\#', '\\#', '\\%'];
var reg = new RegExp('(.*['+ list.join(',') + '].*['+ list.join(',') +'])');
if (reg.test("MySuperPassword!#_123")) {
score += 5;
}
You do not need to separate chars by , in regex:
var list = "[\\!##\\$%\\^&\\*\\?_~]";
var your_regex = new RegExp(".*" + list + ".*" + list);
if (your_regex.test(password)){
score += 5;
}
Why would you need a regex?
var list = ['!','#','#','$','%','^','&','*','?','_','~','[',']','{','}','(',')'],
score = 0;
for (var i=list.length;i--;) {
if ( password.indexOf(list[i]) ) score++;
}
FIDDLE
Related
I have a search box and i need to grab the value of this search and match all DIV which data-* value is starting with the search value.
Cases:
Search value: 201
Should match: data-year="2011", data-year="2012", data-year="2013"
Should fail: data-year="2009", data-year="2001"
This is what i come up with so far:
\\b(?=\\w*[" + token + "])\\w+\\b
token is a dynamic value from the search box. Therefore i need to use RegExp
This is working but it match all the value which contain 2 or 0 or 1 (for my understanding). so 2009 is valid match as well. :/
I also try to add the caret at the beginning in order to match the characthers just at the beginning of the world but clearly i'm missing something here:
^\\b(?=\\w*[" + token + "])\\w+\\b
The whole code is:
var token = '200'; // should fail
var tokenTwo = '201'; // shoudl work
var dataAtt = $('#div').data('year').toString();
var regexExpression ="^\\b(?=\\w*\\d*[" + token + "])\\w+\\d+\\b";
var regEXPRES = "^.*" + token + ".*$";
var regex = new RegExp(regexExpression, "i");
if( dataAtt.match(regex) ){
console.log(dataAtt);
alert('yey!!!');
} else {
alert('nope!! )')
}
and here is the JsFiddle http://jsfiddle.net/tk5m8coo/
p.s. I shouldn't have any cases where token is precede or follow by other characters, but if anyone as idea how to check also this, would be great. Just in case of any typo like s2015.
Problem is that you're putting your search value inside a character class when you enclose your regex by wrapping around [...].
You also don't need a lookahead. You can just use:
var regex = new RegExp("\\b\\w*" + value + "\\w*\\b");
To make sure search value is matched within a full word. (\w includes digits also so no need to use \d).
Full code:
var value = '20'; //token
var html = $("#div").html(); //data.()
var dataAtt = $('#div').data('year').toString();
var regex = new RegExp("\\b\\w*" + value + "\\w*\\b");
if( dataAtt.match(regex) ){
console.log(dataAtt + " matched");
} else {
console.log('nope')
}
Updated JS Fiddle
Or you can use indexOf():
var value = '20';
var html = $("#div").html();
var dataAtt = $('#div').data('year').toString();
if( dataAtt.indexOf(value) >= 0 ){
console.log('yey!!!');
} else {
console.log('nein!! )')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id ="div" data-year="2015">
what bozo where 2015
</div>
Your regex is using a character class which will match any of the characters inside the square brackets. Remove the square brackets:
^\\b(?=\\w*" + token + ".*)\\w+\\b
I have to validate a field. The field should be numeric, should not contain all the same digits (like 555555, 111111) . I need a regular expression to check this. I need to know how can I check if it contains all same digits.
tried few solutions like following but didn't worked
these three didn't work
var reg_exp = new RegExp('/^([0-9a-z])\1+$/gm');
var reg_exp = new RegExp('/^(\d)\1*$/');
var reg_exp = new RegExp('([0-9])\\1{5}');
This one working partly bcoz here it fixes to specific number of digits e.g. {6} in the expample to a specific number but i need a solution so that i can apply this to any number of digits
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = "111111112";
var reg_exp = new RegExp('([0-9]){6}');
alert(reg_exp.test(str));
}
</script>
</body>
</html>
based on http://stackoverflow.com/users/3832970/wiktor-stribi%C5%BCew tried this and it worked for string which have length more than 2
function myFunction() {
var str = "222";
var reg_exp = /^(\d)\1+$/; // new RegExp('([0-9]){6}');
alert(reg_exp.test(str));
}
returns true and
function myFunction() {
var str = "221";
var reg_exp = /^(\d)\1+$/; // new RegExp('([0-9]){6}');
alert(reg_exp.test(str));
}
returns false
but the issue is that for
function myFunction() {
var str = "22";
var reg_exp = /^(\d)\1+$/; // new RegExp('([0-9]){6}');
alert(reg_exp.test(str));
}
or
function myFunction() {
var str = "11";
var reg_exp = /^(\d)\1+$/; // new RegExp('([0-9]){6}');
alert(reg_exp.test(str));
}
it returns false
I need a regex which can work for one digits numbers as well. and var str = "1"; or var str = "22"; should return true. Basically the numbers should have atleast two unique digits
A regex that will match an all-numeric string that has no 2 unique digits is
/^(\d)(?:\1+)?$/
See the regex demo.
Explanation:
^ - start of string
(\d) - Group 1 that captures a single digit (the first one in the string)
(?:\1+)? - an optional (as ? matches one or zero occurrences) non-capturing group that matches the same digit that was captured with Group 1
$ - end of string.
In JS:
document.body.innerHTML = "22: " + /^(\d)(?:\1+)?$/.test("22") + " as there are no unique digits, 2-digit string";
document.body.innerHTML += "<br/>12: " + /^(\d)(?:\1+)?$/.test("12") + " as there are 2 unique digits";
document.body.innerHTML += "<br/>1: " + /^(\d)(?:\1+)?$/.test("1") + " as there is just 1 digit, no 2 unique digits";
document.body.innerHTML += "<br/>-------- OR, with negation ----------";//or
document.body.innerHTML += "<br/>22: " + !/^(\d)(?:\1+)?$/.test("22") + " as there are no unique digits, 2-digit string";
document.body.innerHTML += "<br/>12: " + !/^(\d)(?:\1+)?$/.test("12") + " as there are 2 unique digits";
document.body.innerHTML += "<br/>1: " + !/^(\d)(?:\1+)?$/.test("1") + " as there is just 1 digit, no 2 unique digits";
You can use this pattern (with the matches method that implicitly anchors the pattern on both sides):
(\d)\1*+\d+
(don't forget to escape the backslashes in the string)
The main idea is to use a possessive quantifier ( *+ ) to forbid backtracking on the back-reference quantifier. Since this quantifier can't be used to backtrack, the following digit can only be different.
If you want to allow single digit strings, you can make the second part optional:
(\d)(?:\1*+\d+)?
or you can add an alternation:
(\d)\1*+\d+|\d
If you want to check the length of the string, (you can obviously do it with the same regex) use the string.length() method.
here my probleme, in some project i need to validate a string, it must be a length of 4 character and contains one and only one number but i don't know it's place (can be "er1t" or "4frt" but not "sdfd" or "4fd5")
i have made a regex which work : (?:[a-z]\d[a-z]{2}|\d[a-z]{3}|[a-z]{2}\d[a-z]|[a-z]{3}\d) but it's not optimised and I don't find how i search for a number in a string in regex, i use a javascript regex.
Thank in advance,
ekanS
Looks like you can use
^(?=[a-z]*\d[a-z]*$)[a-z\d]{4}$
Demo.
In short, we can set a (?=\D*\d\D*$) condition to check if the whole line/string has only 1 number at the very start of a line/string. Then we can allow any lowercase letters and numbers.
If you plan to allow upper case letters, add A-Z to the character class, or use i option.
function isValid(code) {
var re = /^(?=[a-z]*\d[a-z]*$)[a-z\d]{4}$/gm;
if ((m = re.exec(code)) !== null) {
document.getElementById("res").innerHTML = document.getElementById("res").innerHTML + "<br>" + m[0] + " is <font color=\"#0000FF\">valid</font>.";
}
else {
document.getElementById("res").innerHTML = document.getElementById("res").innerHTML + "<br>" + code + " is <font color=\"#FF0000\">not valid</font>.";
}
}
isValid('er1t');
isValid('4frt');
isValid('sdfd');
isValid('4fd5');
isValid('ffd5');
document.getElementById("res").innerHTML + "</font>"
<div id="res"><font face="Arial"><b>Valid codes:</b><font face="Tahoma"><div>
I'm trying to validate postal code ranges using Javascript and the framework that supplies the country specific validation rule to the method uses regular expressions.
Is there a way to validate (using regex match/test/any other js regex functions) if the number of characters on both sides of the range delimiter (its colon in this case) is same ?
e.g.
85001:85255 or A9A 9AA:A9A 9ZZ is valid (both sides have same number of characters)
Whereas,
85001:255 or A9A 9AA:9ZZ is invalid (different number of characters in x vs y for x:y)
Thanks
Here a little bit less verbose version of RegExp profided by #tak3r
var r = /^(.{1}:.{1}|.{2}:.{2}|.{3}:.{3}|.{4}:.{4}|.{5}:.{5}|.{6}:.{6}|.{7}:.{7})$/
one paradigm of regular expressions is that they cannot count.
However, you can "hack it" like so if you know the max length of the number of chars on a side. Assuming a max-length of 4:
var code = '8500:1234';
/\b((.:.)|(..:..)|(...:...)|(....:....))\b/.test(code)
if you don't want to write this by hand, you can generate the regexp like so:
var max_length = 6;
var delimiter = ':';
var regexp = [];
for (var i=1; i<=max_length; ++i) {
var side = '';
for (var j=1; j<=i; ++j) {
side += '.';
}
regexp.push('(' + side + delimiter + side + ')');
}
regexp = '\b(' + regexp.join('|') + ')\b';
regexp = new RegExp(regexp);
You could simply split the tokens and compare the lengths:
var range = "123:567";
var tokens = range.split(":");
var valid = tokens[0].length === tokens[1].length;
function compareValues(str){
var str_array = str.split(':');
return (str_array[0].length===str_array[1].length);
}
alert(compareValues('A9A 9AA:A9A 9ZZ'));
alert(compareValues('85001:255'));
jsfiddle : http://jsfiddle.net/EU7uB/4/
Just an added thought, given your two postal codes:
var s1 = "85001:85255";
var s2 = "A9A 9AA:A9A 9ZZ";
This regex will test for a pattern of either 5 digits before and after the colon, OR 3 of either a letter or number followed by a space and then another 3 of either a letter or number before and after the colon.
//var re = /(((\w|\d){3}\s(\w|\d){3}:(\w|\d){3}\s(\w|\d){3})|(\d{5}:\d{5}))/;
var re = /((\w{3}\s\w{3}:\w{3}\s\w{3})|(\d{5}:\d{5}))/;
alert(re.test(s1));
alert(re.test(s2));
You can use capture parentheses on both side of the colon and then test their
Lengths for equality.
var myString = "85001:85255";
var myRegexp = /^([\w][\w\s]+):([\w][\w\s]+)$/;
var match = myRegexp.exec(myString);
if (match[1].length === match[2].length) {
alert("There is a match!")
}
else {
alert("Not a match")
}
//There is a match!
i need to check if a textarea contains some special characters, so i need to count them 2 (SMS lenght).
I wrote this piece of code but seems that it doesn't find no special chars, also if write only "€€€"
Could you please help me? Also if you would to rewrite directly function, without problem. Thank tou!
var SPECIAL_CHARS = Array('€', '%');
function charUsed() {
var count = $('#text').val().length;
var chars = $('#text').val().split("");
var numberOfSpecialChars = 0;
if ($.inArray(chars, SPECIAL_CHARS) > -1) {
numberOfSpecialChars++;
}
return count + numberOfSpecialChars;
} // function
A rewrite :
var nbSpecialChars = $('#text').val().split(/[€%]/).length - 1;
The idea is to make an array of strings, using your special characters as separator :
'some € chars %' => ["some ", " chars ", ""]
and then use the length of this array to deduce the count of those chars. There are many other (faster) solutions but this one is short.
http://jsfiddle.net/KSm7J/
var chars = $('#text').val().match(/[€%]/g).length;
alert(chars);