I've working on a javascript regex that I intend to use with the jquery validate plugin (I'll add this as an additional method). It must (among other rules):
test if at least one of the following special characters is entered:
!, ", #, $, %, &, ', (, ), *, +,-, .,/, :, ;, <, =, >, ?, #, [, \, ], ^, _, `, {, |, }, ~
not allow 3 consecutive identical characters:
passed:
aa
99
++
not passed:
aaa
999
+++
The problem with my regex is that is having problem with these mentioned rules:
I think the issue is related to escaping and I've tried escaping + and - to no avail. Can anyone help! This is my regex: http://regexr.com/3ack3
This is one of those requirements where you can really simplify your life by using multiple regexes, rather than trying to cram all the logic into one complex regex with many assertions. Here's some JavaScript that implements your requirement:
var specialCharRegex = /[!"#$%&'()*+.\/:;<=>?#\[\\\]^_`{|}~-]/;
var threeConsecutiveRegex = /(.)\1\1/;
var input = prompt();
if (specialCharRegex.test(input) && !threeConsecutiveRegex.test(input)) {
alert('passed');
} else {
alert('failed');
} // end if
http://jsfiddle.net/t8609xv2/
Some notes on the trickier points:
inside the bracket expression, the following four special characters had to be backslash-escaped: /[\]. (Forward slash because it delimits the regex, backslash because it's the escape character, and the brackets because they delimit the bracket expression.)
inside the bracket expression, the dash had to be moved to the end, because otherwise it would likely specify a character range. When at the end, it never specifies a range, so it's always safer to put it there.
This modular approach also benefits maintainability, as you will more easily be able to make changes (modify/add/remove regexes, or change the if-test logic) at a later point in time.
Another benefit is that you could test each regex independently, which could allow you to provide a more accurate error message to the user, as opposed to just saying something like "invalid password".
Edit: Here's how you can whitelist the chars that are accepted in the input:
var specialCharRegex = /[!"#$%&'()*+.\/:;<=>?#\[\\\]^_`{|}~-]/;
var threeConsecutiveRegex = /(.)\1\1/;
var nonWhitelistCharRegex = /[^a-zA-Z0-9!"#$%&'()*+.\/:;<=>?#\[\\\]^_`{|}~-]/;
var input = prompt();
if (specialCharRegex.test(input) && !threeConsecutiveRegex.test(input) && !nonWhitelistCharRegex.test(input)) {
alert('passed');
} else {
alert('failed');
} // end if
http://jsfiddle.net/t8609xv2/2/
^(?=.*[!"#$%&'()*+,,\/:;<=>?#\[\]^_`{|}~-])(?!.*(.)\1\1).*$
Try this.See demo.
https://regex101.com/r/wX9fR1/10
You need a positive lookahead to check for special characters.
And
A negative lookahead to check if a character is is there 3 times.
You can use this regex:
^(?!.*?(.)\1{2})(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\D*\d)(?=.*?[!##$%^&*()_=\[\]{};':"\\|,.<>\/?+-]).{8,20}$
RegEx Demo
You might be able to shorten it using:
^(?!.*?(.)\1{2})(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\D*\d)(?=.*?[\W_]).{8,20}$
i.e. using non-word property \W instead of listing each and every special character.
Related
I am facing an issue with a regular expression while trying to block any string which has minus(-) in the beginning of some white listed characters.
^(?!-.*$).([a-zA-Z0-9-:#\\,()\\/\\.]+)$
It is blocking minus(-) at place and allowing it any where in the character sequence but this regex is not working if the passed string is single character.
For e.g A or 9 etc.
Please help me out with this or give me a good regex to do the task.
Your pattern requires at least 2 chars in the input string because there is a dot after the first lookahead and then a character class follows that has + after it (that is, at least 1 occurrence must be present in the string).
So, you need to remove the dot. Also, you do not need to escape any special char inside a character class. Besides, to avoid matching strings atarting with - a mere (?!-) will suffice, no need adding .*$ there. You may use
^(?!-)[a-zA-Z0-9:#,()/.-]+$
See the regex demo. Remember to escape / if used in a regex literal notation in JavaScript, there is no need to escape it in a constructor notation or in a Java regex pattern.
Details
^ - start of a string
(?!-) - cannot start with -
[a-zA-Z0-9:#,()/.-]+ - 1 or more ASCII letters, digits and special chars defined in the character class (:, #, ,, (, ), /, ., -)
$ - end of string.
If i understand correctly, and you don't want a minus at the beginning, does ^[^-].* work as a regex for you? Java's "matches" would return false if it starts with minus
There is a method in a String class that provides you exactly what you are asking for - it's a startsWith() method - you could use this method in your code like this (you can translate it as "If the given String doesn't start with -, doSomething, in other case do the else part, that can contain some code or might be empty if you want nothing to be done if the given String starts with - ") :
if(!(yourString.startsWith("-"))) {
doSomething()
} else {
doNothingOrProvideAnyInformationAboutWrongInput()
}
I think that it can help you.
^(?!-).*[a-zA-Z0-9-:#\\,()\/\\.]+$
I am using following regex if I pass lenghty string to check, regex101.com showing timeout message. Is there any ideal length to test regular expresssion?
^(\d+[\s\r\n\t,]*){1,100}$
https://regex101.com/r/eC5qO7/1
I suggest running a split, then making sure what is split is a number, so:
var test = "123,456 789 101112 asdf";
var numbers = test.split(/\s*,\s*|\s+/);
numbers.forEach(function(n) {
if (n % 1 !== 0) {
alert(n + " is not an integer");
}
});
The catastrophic backtracking is caused by the fact that the [\s\r\n\t,] character class has a * quantifier applied to it, and then a + quantifier is set to the whole group. The regex backtracks into each digit to search for optional whitespace and commas, which creates a huge number of possibilities that the engine tries before running into the "catastrophe".
Besides, there is another potential bottleneck: \s in the character class can also match \r, \n and \t. See see Do character classes present the same risk?.
Without atomic groups and possessive quantifiers, the regex optimization is only possible by means of making one of the "separators" obligatory. In this case, it is clearly a comma (judging by the example string). Since you just want to validate the number of input numbers separated with commas and optional spaces, you can use a simpler regex:
^(?:[0-9]+\s*,\s*){1,100}$
Here, it fails gracefully, and here it matches the string OK.
If a comma at the end is optional, use
^(?:\d+\s*,\s*){1,99}\d+,?\s*$
See demo
Also note you do not need the i modifier, as there are no letters in the pattern.
I am facing an issue in JavaScript form validation. I have to store number in this format 1-74347064527
I have tried these regular expressions but not worked properly:
var srNo =/^[-0-9]*$/;
var srNo = /^[0-9]+(-[0-9]+)+$/;
var srNo=/^([0-9]+-)*[0-9]+$/;
Suggest some regex for this.
Kind regards.
This should work unless you have additional constraints:
var srNo = /^\d+-\d+$/;
If you prefer the [0-9] syntax:
var srNo = /^[0-9]+-[0-9]+$/;
When in a character class ([ ]), dash ( - ) has a special meaning in regular expressions - it means "range", eg. a-z means from 'a' to 'z'. You're not escaping it, so your RegExps are not even correct (at least not in every language).
Update: It appears, that this syntax is correct when dash is not surrounded by other characters (when it's placed at the beginning or end of the character class). Sorry for confusion.
Try this instead:
/^\d\-\d+$/
It matches strings that begin with one digit, followed by a dash, and then by one or more digits.
var regex = /^\d{1}-?\d{11}$/g
window.alert(regex.test('1-74347064527'));
In my current regular expression, I am negating digits:
$(function(){
$("#somewhat").bind("keyup",
function(event) {
var regex = /^[\D]*$/;
alert(regex.test($("#somewhat").val()));
});
});
What I have in my mind is to add some special characters on which I should negate, !##$%^&*()_+=<>.?/~`:;" , and leaving dash, apostrophe ( -' ) to the valid list. I'm still kind of dizzy on this regular expression thing. To test with, I added + on the regex,
var regex = /^[\D+]*$/;
When I test it, the alert box returns TRUE, which is not I am expecting.
Inside [ ] please add all the characters you don't want to allow.
/^((?![\d!##$%^&*()_+=<>.?/~`:;"]).)*$/
But can we rely on negating given characters ? because user will be able to enter any character other than these. If you want to allow non-English characters, I would suggest you to use Unicode ranges
see this : http://kourge.net/projects/regexp-unicode-block
[\D+] means "any character that is +, or that is not a digit"; so it's actually equivalent to plain old \D or [\D], since + itself isn't a digit.
To get the meaning of "any character that is neither + nor a digit", you'd have to write [^\d+].
(\D or [\D] is equivalent to [^\d], but its negative-ness doesn't extend beyond that.)
I have a string and I want to validate that string so that it must not contain certain characters like '/' '\' '&' ';' etc... How can I validate all that at once?
You can solve this with regular expressions!
mystring = "hello"
yourstring = "bad & string"
validRegEx = /^[^\\\/&]*$/
alert(mystring.match(validRegEx))
alert(yourstring.match(validRegEx))
matching against the regex returns the string if it is ok, or null if its invalid!
Explanation:
JavaScript RegEx Literals are delimited like strings, but with slashes (/'s) instead of quotes ("'s).
The first and last characters of the validRegEx cause it to match against the whole string, instead of just part, the carat anchors it to the beginning, and the dollar sign to the end.
The part between the brackets ([ and ]) are a character class, which matches any character so long as it's in the class. The first character inside that, a carat, means that the class is negated, to match the characters not mentioned in the character class. If it had been omited, the class would match the characters it specifies.
The next two sequences, \\ and \/ are backslash escaped because the backslash by itself would be an escape sequence for something else, and the forward slash would confuse the parser into thinking that it had reached the end of the regex, (exactly similar to escaping quotes in strings).
The ampersand (&) has no special meaning and is unescaped.
The remaining character, the kleene star, (*) means that whatever preceeded it should be matched zero or more times, so that the character class will eat as many characters that are not forward or backward slashes or ampersands, including none if it cant find any. If you wanted to make sure the matched string was non-empty, you can replace it with a plus (+).
I would use regular expressions.
See this guide from Mozillla.org. This article does also give a good introduction to regular expressions in JavaScript.
Here is a good article on Javascript validation. Remember you will need to validate on the server side too. Javascript validation can easily be circumvented, so it should never be used for security reasons such as preventing SQL Injection or XSS attacks.
You could learn regular expressions, or (probably simpler if you only check for one character at a time) you could have a list of characters and then some kind of sanitize function to remove each one from the string.
var myString = "An /invalid &string;";
var charList = ['/', '\\', '&', ';']; // etc...
function sanitize(input, list) {
for (char in list) {
input = input.replace(char, '');
}
return input
}
So then:
sanitize(myString, charList) // returns "An invalid string"
You can use the test method, with regular expressions:
function validString(input){
return !(/[\\/&;]/.test(input));
}
validString('test;') //false
You can use regex. For example if your string matches:
[\\/&;]+
then it is not valid. Look at:
http://www.regular-expressions.info/javascriptexample.html
You could probably use a regular expression.
As the others have answered you can solve this with regexp but remember to also check the value server-side. There is no guarantee that the user has JavaScript activated. Never trust user input!