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));
});
Related
I'm trying to take only expressions like 'A==1' or 'D1 >= 2' from a string (including spaces).
For example:
From - '(A == 3 AND B == 4) OR ( A==1 AND B==2)'
I expect to get: [A == 3, B == 4, A==1, B==2].
Here's my code:
let myString = '(A == 3 AND B == 4) OR ( A==1 AND B==2)';
const result = myString.match(/[a-z0-9\s]+(>|<|==|>=|<=|!=|\s)\d/gi);
console.log(result); //result => [A == 3 ,AND B == 4,A==1 ,AND B==2]
I want my regex to take only the specific pattern of {param}{operator}{param} but with blank spaces.
I tried many ways, but none was successful.
I would appreciate any help.
You might write the pattern with the case insensitive flag as:
\b[a-z0-9]+\s*(?:[=!]=|[<>]=?)\s*\d+\b
Explanation
\b A word boundary to prevent a partial word match
[a-z0-9]+ Match 1+ chars a-z or a digit 0-9
\s* Match optional whitspace cahrs
(?:[=!]=|[<>]=?) Match either =! == < > <= >=
\s* Match optional whitespace chars
\d+\b 1+ digits and a word boundary
Regex demo
For only leading uppercase chars:
\b[A-Z]+\s*(?:[=!]=|[<>]=?)\s*\d+\b
const regex = /\b[A-Z]+\s*(?:[=!]=|[<>]=?)\s*\d+\b/g;
const s = `(A == 3 AND B == 4) OR ( A==1 AND B==2)`;
console.log(s.match(regex))
Regex demo
Something like this would work:
[a-z\d]+\s*[=<>!]+\s*[a-z\d]
Explanation:
[a-z\d]+\s* - left side of comparison
[=<>!]+ - comparison operators
\s*[a-z\d] - right side of comparison
let myString = '(A == 3 AND B == 4) OR ( A==1 AND B==2)';
const result = myString.match(/[a-z\d]+\s*[=<>!]+\s*[a-z\d]/gi);
console.log(result);
I am trying to create a regex that checks a string and will match a dot, dash or underscore. I only want it to allow a maximum of 3 otherwise it should not match the string.
For example if I enter qwerty-123-123-123 that is okay.
If I enter something-123_world that is okay.
However if I enter qwerty-123-_whatever-something this should not match.
Current regex
My current regex matches the specific characters I want but I can't seem to figure out how to only allow 3 maximum. I thought {1,3} was the answer but that didn't seem to work. I also had a look at ?= positive lookups but not sure if that's correct / even able to get it to do what I want.
You may use
/^[^-_.]*(?:[-_.][^-_.]*){1,3}$/
See the regex demo
Details
^ - start of string
[^-_.]* - any 0+ chars other than -, _ and .
(?:[-_.][^-_.]*){1,3} - one, two or three occurrences of
[-_.] - a -, _ or .
[^-_.]* - any 0+ chars other than -, _ and .
$ - end of string.
The other option apart from Regex would be to use JavaScript!
let str1 = 'qwerty-123-123-123';
let str2 = 'something-123_world';
let str3 = 'qwerty-123-_whatever-something';
const regex = /[._-]/g;
let min = 1;
let max = 3;
function validate(txt) {
var len = txt.match(regex).length;
if(len >= min && len <= max)
return true;
return false;
}
console.log(validate(str1) ? 'Valid' : 'Invalid');
console.log(validate(str2) ? 'Valid' : 'Invalid');
console.log(validate(str3) ? 'Valid' : 'Invalid');
I was wondering if anyone knows a way for regex to detect that there has been a minimum of x digits used.
For example if I put in a number 6 digit number of 111222 but my regex says there must be at least 3 unique numbers this would cause a valid fail.
but if I had 123456 that would pass because there is more than three unique digits used.
Something like (obviously it wont be like bellow.)
/^[0-9]{6}*3$/
non regex way
var telcstart = $('#num').val(),
telc1 = (telcstart.match(/1/g) || []).length,
telc2 = (telcstart.match(/2/g) || []).length,
telc3 = (telcstart.match(/3/g) || []).length,
telc4 = (telcstart.match(/4/g) || []).length,
telc5 = (telcstart.match(/5/g) || []).length,
telc6 = (telcstart.match(/6/g) || []).length,
telc7 = (telcstart.match(/7/g) || []).length,
telc8 = (telcstart.match(/8/g) || []).length,
telc9 = (telcstart.match(/9/g) || []).length,
telc0 = (telcstart.match(/0/g) || []).length,
totaltelc = "a:" + telc1 + " b:" + telc2 + " c:" + telc3 + " d:" + telc4 + "e:" + telc5 + " f:" + telc6 + " g:" + telc7 + " h:" + telc8 + " i:" + telc9 + " j:" + telc0,
finaltelc = (totaltelc.match(/0/g) || []).length;
if (finaltelc <= 8) {
alert('passed');
} else {
alert('failed');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" id="num" value="123451212111">
^(?=.*(.)(?!$|.*\1))(?=.*(?!\1)(.)(?!$|.*\2))[0-9]+$
function check(value) {
var res = document.getElementById('result');
if (/^(?=.*(.)(?!$|.*\1))(?=.*(?!\1)(.)(?!$|.*\2))[0-9]+$/.test(value)) {
res.innerText = '✓ OK';
} else {
res.innerText = '✗ No match';
}
}
<p>Enter a number with ≥3 different digits</p>
<p><input type=text onkeyup='check(this.value)'> <span id=result></span></p>
Let's split it up:
^
(?=
.*(.) # Pick any character in the string as group 1
(?!$|.*\1) # Ensure this is not the last character, but is the last unique character
)
(?=
.*(?!\1)(.) # Pick another character in the string as group 2
(?!$|.*\2) # Same condition as above
)
[0-9]+
$
The first condition ensures there is a string like ??1??a. The second condition ensures a string like ???2?b, where 1 ≠ a and 2 ≠ b and 1 ≠ 2. From this we can conclude there are at least 3 different characters.
This can be easily generalized to e.g. at least 8 different characters needed:
^
(?=.*(.)(?!$|.*\1))
(?=.*(?!\1)(.)(?!$|.*\2))
(?=.*(?!\1|\2)(.)(?!$|.*\3))
(?=.*(?!\1|\2|\3)(.)(?!$|.*\4))
(?=.*(?!\1|\2|\3|\4)(.)(?!$|.*\5))
(?=.*(?!\1|\2|\3|\4|\5)(.)(?!$|.*\6))
(?=.*(?!\1|\2|\3|\4|\5|\6)(.)(?!$|.*\7))
[0-9]+
$
Because JavaScript only support up to \9, you can't use this method to check more than 10 different characters. At this point you should really question whether regex is a right tool for this job though 😉.
You actually can do this with a regex, but it'll be very ugly and near-incomprehensible.
Looking at just one case, we can write a regex for a string that contains 0, 1, and at least one number from 2 to 9:
/^0(\d)*1(\d)*[2-9](\d)*$/
For each possible pair of numbers, we would have to write a regex like this ad combine all of them using | so that we catch all cases.
There are 10*9 = 90 pairs of distinct digits, and for each group there are 2 permutations, totalling 180 groups.
So we would have to do:
/(^0(\d)*1(\d)*[2-9](\d)*$/)|(^0(\d)*2(\d)*(1|[3-9])(\d)*$/)| ... /
Continuing for all 180 groups. That would be a gigantic regex, and would probably take a very long while to compile.
You should do this validation with code instead of running a regex.
EDIT: Apparently, JavaScript regexes have some extended features which make this doable, namely reusing the value captured by a given group. refer to #kennytm's answerr.
Based on negative lookaheads you can ensure a different digit matches three times:
(\d)\d*?((?!\1)\d)\d*?(?!\1|\2)\d+$
RegEx Demo
(?!\1) negative lookahead to ensure next match is not same as captured group #1
(?!\1|\2) negative lookahead to ensure next match is not same as captured group #1 and group #2
function uniqueDigit(str)
{
var a = 0;
for (var i=0; i<10; i++)
{
(new RegExp( i, 'g')).test(str) && a++;
}
return a
}
console.log(uniqueDigit('10122211100')) // in str
console.log(uniqueDigit(222111333888)) // in int
var a = 123456;
console.log(/^\d{6}$/.test(a) && uniqueDigit(a) > 2) // example
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);
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/