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'));
Related
I have a filename that will be something along the lines of this:
Annual-GDS-Valuation-30th-Dec-2016-082564K.docx
It will contain 5 numbers followed by a single letter, but it may be in a different position in the file name. The leading zero may or may not be there, but it is not required.
This is the code I come up with after checking examples, however SelectedFileClientID is always null
var SelectedFileClientID = files.match(/^d{5}\[a-zA-Z]{1}$/);
I'm not sure what is it I am doing wrong.
Edit:
The 0 has nothing to do with the code I am trying to extract. It may or may not be there, and it could even be a completely different character, or more than one, but has nothing to do with it at all. The client has decided they want to put additional characters there.
There are at least 3 issues with your regex: 1) the pattern is enclosed with anchors, and thus requires a full string match, 2) the d matches a letter d, not a digit, you need \d to match a digit, 3) a \[ matches a literal [, so the character class is ruined.
Use
/\d{5}[a-zA-Z]/
Details:
\d{5} - 5 digits
[a-zA-Z] - an ASCII letter
JS demo:
var s = 'Annual-GDS-Valuation-30th-Dec-2016-082564K.docx';
var m = s.match(/\d{5}[a-zA-Z]/);
console.log(m[0]);
All right, there are a few things wrong...
var matches = files.match(/\-0?(\d{5}[a-zA-Z])\.[a-z]{3,}$/);
var SelectedFileClientID = matches ? matches[1] : '';
So:
First, I get the matches on your string -- .match()
Then, your file name will not start with the digits - so drop the ^
You had forgotten the backslash for digits: \d
Do not backslash your square bracket - it's here used as a regular expression token
no need for the {1} for your letters: the square bracket content is enough as it will match one, and only one letter.
Hope this helps!
Try this pattern , \d{5}[a-zA-Z]
Try - 0?\d{5}[azA-Z]
As you mentioned 0 may or may not be there. so 0? will take that into account.
Alternatively it can be done like this. which can match any random character.
(\w+|\W+|\d+)?\d{5}[azA-Z]
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.
I'm trying to create a validation for a password field which allows only the a-zA-Z0-9 characters and .!##$%^&*()_+-=
I can't seem to get the hang of it.
What's the difference when using regex = /a-zA-Z0-9/g and regex = /[a-zA-Z0-9]/ and which chars from .!##$%^&*()_+-= are needed to be escaped?
What I've tried up to now is:
var regex = /a-zA-Z0-9!##\$%\^\&*\)\(+=._-/g
but with no success
var regex = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]+$/g
Should work
Also may want to have a minimum length i.e. 6 characters
var regex = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]{6,}$/g
a sleaker way to match special chars:
/\W|_/g
\W Matches any character that is not a word character (alphanumeric & underscore).
Underscore is considered a special character so
add boolean to either match a special character or _
What's the difference?
/[a-zA-Z0-9]/ is a character class which matches one character that is inside the class. It consists of three ranges.
/a-zA-Z0-9/ does mean the literal sequence of those 9 characters.
Which chars from .!##$%^&*()_+-= are needed to be escaped?
Inside a character class, only the minus (if not at the end) and the circumflex (if at the beginning). Outside of a charclass, .$^*+() have a special meaning and need to be escaped to match literally.
allows only the a-zA-Z0-9 characters and .!##$%^&*()_+-=
Put them in a character class then, let them repeat and require to match the whole string with them by anchors:
var regex = /^[a-zA-Z0-9!##$%\^&*)(+=._-]*$/
You can be specific by testing for not valid characters. This will return true for anything not alphanumeric and space:
var specials = /[^A-Za-z 0-9]/g;
return specials.test(input.val());
Complete set of special characters:
/[\!\#\#\$\%\^\&\*\)\(\+\=\.\<\>\{\}\[\]\:\;\'\"\|\~\`\_\-]/g
To answer your question:
var regular_expression = /^[A-Za-z0-9\!\#\#\$\%\^\&\*\)\(+\=\._-]+$/g
How about this:-
var regularExpression = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{6,}$/;
It will allow a minimum of 6 characters including numbers, alphabets, and special characters
There are some issue with above written Regex.
This works perfectly.
^[a-zA-Z\d\-_.,\s]+$
Only allowed special characters are included here and can be extended after comma.
// Regex for special symbols
var regex_symbols= /[-!$%^&*()_+|~=`{}\[\]:\/;<>?,.##]/;
This regex works well for me to validate password:
/[ !"#$%&'()*+,-./:;<=>?#[\\\]^_`{|}~]/
This list of special characters (including white space and punctuation) was taken from here: https://www.owasp.org/index.php/Password_special_characters. It was changed a bit, cause backslash ('\') and closing bracket (']') had to be escaped for proper work of the regex. That's why two additional backslash characters were added.
Regex for minimum 8 char, one alpha, one numeric and one special char:
/^(?=.*[A-Za-z])(?=.*\d)(?=.*[!##$%^&*])[A-Za-z\d!##$%^&*]{8,}$/
this is the actual regex only match:
/[-!$%^&*()_+|~=`{}[:;<>?,.##\]]/g
You can use this to find and replace any special characters like in Worpress's slug
const regex = /[`~!##$%^&*()-_+{}[\]\\|,.//?;':"]/g
let slug = label.replace(regex, '')
function nameInput(limitField)
{
//LimitFile here is a text input and this function is passed to the text
onInput
var inputString = limitField.value;
// here we capture all illegal chars by adding a ^ inside the class,
// And overwrite them with "".
var newStr = inputString.replace(/[^a-zA-Z-\-\']/g, "");
limitField.value = newStr;
}
This function only allows alphabets, both lower case and upper case and - and ' characters. May help you build yours.
This works for me in React Native:
[~_!##$%^&*()\\[\\],.?":;{}|<>=+()-\\s\\/`\'\]
Here's my reference for the list of special characters:
https://owasp.org/www-community/password-special-characters
If we need to allow only number and symbols (- and .) then we can use the following pattern
const filterParams = {
allowedCharPattern: '\\d\\-\\.', // declaring regex pattern
numberParser: text => {
return text == null ? null : parseFloat(text)
}
}
The following JavaScript outputs nothing (not even "false"), and indeed stops any other JavaScript on the page from running:
var pattern = new RegExp(/[_-%]/);
document.write(pattern.test("foo"));
What is it about this regular expression that does this? If any one of the three characters (_, -, or %) is removed, everything works normally. And if the order of the three characters is changed at all, everything works normally.
A hyphen in a [ ] block is used for ranges. So _ to % is invalid.
You can escape it:
var pattern = new RegExp(/[_\-%]/);
or move to the start:
var pattern = new RegExp(/[-_%]/);
or to the end:
var pattern = new RegExp(/[_%-]/);
Since regex knows that a hyphen at the start (or end, thanks BrunoLM!) means a literal hyphen and not a range.
It's because in the interpreter thinks it's dealing with a range. Just like /[a-z]/ will match any character between a and z, /[_-%]/ will (try to) match any character between _ and %. This doesn't make sense, so JavaScript stops. Putting the hyphen as the first or last character will fix the issue.
It's the dash in the middle. JavaScript treats [_-%] as a character class range, similar to [A-Z]. I'm guessing the browser you're using simply doesn't handle this case very well. I suggest moving the hyphen to the front, or escaping it with a backslash (\-).
Use the following instead:
/[-_%]/
The - would have been interpreted to be a range. You can also use \-
Need a function to strip off a set of illegal character in javascript: |&;$%#"<>()+,
This is a classic problem to be solved with regexes, which means now I have 2 problems.
This is what I've got so far:
var cleanString = dirtyString.replace(/\|&;\$%#"<>\(\)\+,/g, "");
I am escaping the regex special chars with a backslash but I am having a hard time trying to understand what's going on.
If I try with single literals in isolation most of them seem to work, but once I put them together in the same regex depending on the order the replace is broken.
i.e. this won't work --> dirtyString.replace(/\|<>/g, ""):
Help appreciated!
What you need are character classes. In that, you've only to worry about the ], \ and - characters (and ^ if you're placing it straight after the beginning of the character class "[" ).
Syntax: [characters] where characters is a list with characters.
Example:
var cleanString = dirtyString.replace(/[|&;$%#"<>()+,]/g, "");
I tend to look at it from the inverse perspective which may be what you intended:
What characters do I want to allow?
This is because there could be lots of characters that make in into a string somehow that blow stuff up that you wouldn't expect.
For example this one only allows for letters and numbers removing groups of invalid characters replacing them with a hypen:
"This¢£«±Ÿ÷could&*()\/<>be!##$%^bad".replace(/([^a-z0-9]+)/gi, '-');
//Result: "This-could-be-bad"
You need to wrap them all in a character class. The current version means replace this sequence of characters with an empty string. When wrapped in square brackets it means replace any of these characters with an empty string.
var cleanString = dirtyString.replace(/[\|&;\$%#"<>\(\)\+,]/g, "");
Put them in brackets []:
var cleanString = dirtyString.replace(/[\|&;\$%#"<>\(\)\+,]/g, "");