I want to create a RegExp validation in JavaScript for string which can have 3 parts:
P1-P2-P3
With following rules:
P1, P2 and P3 can only be digits
each part can be 1-13 digits long
entire string can not be longer then 20 characters
P2 and P3 parts are optional (meaning 34 is already a valid string, or 34-6565 or, 566-233455-23232).
Currently I have this, but I am missing the entire string length and I don't know how to define optional parts:
/^.\d{1,13}-\d{1,13}-\d{1,13}$/
Here are few valid entries: 5656, 33434-2323-45, 12-4345-12, 1234567890123-123456, 1234567890123-12-56
Invalid entries: 34453454351234566787, 1234567890123-1234567890123, 23455-233-123-3434, 34sd1322-23, 31234as, ...
You can use:
^(?=\d{1,13}(-\d{1,13}){0,2}$)[\d-]{1,20}$
Online Demo: http://regex101.com/r/sM6wQ7
Explanation:
Try this:
/(^\d{1,13}(-\d{1,13})?(-\d{1,13})?$){1,20}/
? means 0 or 1 of this, so this is useful for optional parts.
{1,20} at the end of the whole string to check it wont be longer than 20.
/^(?!.{21,})\d{1,13}(-\d{1,13}){0,2}$/
(?!.{21,}) at the beginning - negative lookahead meaning: not more than 20 characters.
The total string length check must be separated; the rest can be done with regular expressions:
var re = /^\d{1,13}(?:\-\d{1,13}){0,2}$/;
if (str.length <= 20 && str.match(re)) {
// valid
}
Try this one :
/^(?=.{0,20}$)\d{1,13}(-\d{1,13}){0,2}$/
Description :
^ beginning of the input
(?=.{0,20}$) followed by any char, 0 or 20 times, + end of the input
\d{1,13} a digit, 1 or 13 times
(-\d{1,13}){0,2} a dash + same as above, 0 or 2 times
$ end of the input
More on regular expressions : http://www.javascriptkit.com/javatutors/redev.shtml.
(\d{1,13}-){0,2}(\d{1,13})
Matches two sets of numbers of up to 13 digits of length followed by a dash, then a set of numbers of up to 13 digits of length. This approach is extensible, because you just need to change the number after the first capturing group to change the amount of number parts you want. I would recommend you checking via code if the string's length is appropriate before validating trough Regex. It will be faster and more readable.
Example: http://regex101.com/r/wI7uX1
You could also do this via Javascript, and it may be quite faster: http://jsfiddle.net/sauYY/
Related
I need to write a JavaScript program where it validates input.
Requirement:
Input will have a specific prefix. (eg: --NAME--)
After this prefix, there can be any characters. (eg:
--NAME--any-name_wit#-any*_special_char##$%)
Minimum length of total input (or length of suffix) should be 50 (for example)
I was able to write regex for the first two points, but I couldn't include the final point.
here is what I have tried for the first two points.
input.match(^--NAME--(.*)$)
Use pattern /^--NAME--.{42,}$/
.{42,} - This will match 42 or more characters. The total will be 50 including the prefix (--NAME--).
const regex = /^--NAME--.{42,}$/
console.log(regex.test("--NAME--C$#V"))
console.log(regex.test("--NAME--C$#Vf34F#$f3ftbalc93h34vs#$3gfsddn;yu67u4g3dfvrv34f3f3ff"))
Demo in regex101.com
You can use a lookahead assertion for length:
/^(?=.{50})--NAME--.*$/
From start, at least 50 characters, starting with --NAME--.
I am trying create regex witch will start with some number like 230, 420, 7456. Then could be some number in interval 1-9 but the final length must be 9.
For example 230888333 or 745623777
I create this:
([(230|420|7456)[0-9]{1,}]{9})
But it is not correct. Any idea how to make this correct?
Thaks.
The pattern that you tried is not anchored, and the current notation uses a character class [...] instead of a grouping (the ]{9} part at the end repeats 9 times a ] char)
If you use C# then use [0-9] to match a digit 0-9.
You can either assert 9 digits in total:
^(?=[0-9]{9}$)(?:230|420|7456)[0-9]+$
Regex demo
Or write an alternation for different leading lengths of digits:
^(?:(?:230|420)[0-9]{6}|7456[0-9]{5})$
Regex demo
You can simply add a check for length first and then simple regex
function checkString(str){
return str.length === 9 && /^(?:230|420|7456)\d+$/.test(str)
}
console.log(checkString("230888333"))
console.log(checkString("745623777"))
console.log(checkString("123"))
console.log(checkString("230888333123"))
I have a couple of regex which I am planning to combine.
So the first regex is as below (allows amounts with particular thousand and decimal separators)
"^-?(\\d+|\\d{1,3}(,\\d{3})*)?(\\.(\\d+)?)?$"
I have similar other regexes (based on different locales e.g. other one would have comma as the decimal separator)
So with the above regex, following are Valid/Invalid values
123.11 (Valid)
1'23 (Invalid)
With the second regex, I want that the string can contain a max of 13 digits (including before or after the decimal)
^[^\\d]*?(\\d|\\d[^\\d]+){0,13}$
With the above regex, following are Valid/Invalid values
1234567890123 (Valid - 13 digits)
12345678901234 (Invalid - 14 digits)
1234567890.123 (Valid as 13 digits...10.3)
1234567890.1234 (Invalid as 14 digits...10.4)
Is it possible to somehow consolidate the 2 regex?
However, I do not want to touch the first regex (have different combinations based on different locales). But it would be nice to somehow dynamically append the 2nd regex into the first one ?
So, I am flexible with the 2nd regex as that is not based on any locale, but is going to be the same always and mainly validates for max of 13 digits in the string.
I'll then validate my string using the consolidated regex.
You may keep the first pattern as is, and just prepend it with
(?=^\D*(?:\d\D*){0,13}$)
The (?=^\D*(?:\d\D*){0,13}$) pattern represents a positive lookahead that matches a location that is immediately followed with
^ - start of string
\D* - 0+ non-digits
(?:\d\D*){0,13} - 0 to 13 occurrences of a digit followed with a non-digit char
$ - end of string.
Full JavaScript regex definition:
var regex1 = "^-?(\\d+|\\d{1,3}(,\\d{3})*)?(\\.(\\d+)?)?$"; // Not to be touched
var consolidated_regex = "(?=^\\D*(?:\\d\\D*){0,13}$)" + regex1;
See full regex demo.
Details
I have the following specifications for a regex:
-> The string starts with a string of three numbers
-> It is followed by a '-'
-> That is followed by three uppercase vowels
-> That is followed by a '-'
-> That is followed by three numbers
-> That is followed by a final '-'
-> That is followed by the last three uppercase vowels.
-> Second set of numbers can not equal the first.
-> The second group of letters can not equal the first.
-> The groups of numbers may not contain zero.
A passable string is:
368-IOU-789-AIO.
An invalid string is:
368-AEO-368-AEI
354-AOU-431-AOU
Currently, I have something like this:
([0-9]+[0-9]+[0-9]+[/AEIOU/]+[0-9]+[0-9]+[0-9])
What you have won't work since + means "one or more of". For example, the sequence [0-9]+[0-9]+[0-9]+ will match anywhere between three and an infinite number of digits.
In addition, your current attempt:
allows for one to an infinite number of vowels (and possibly / character);
doesn't require a vowel set at the end;
doesn't require the - separators; and
may allow for arbitrary content before and after the match.
You should be able to use the {count} specifier to get an exact quantity. All but one of those limitations can be done with any basic regex engine, with something like:
^[1-9]{3}-[AEIOU]{3}-[1-9]{3}-[AEIOU]{3}$
The ^ and $ anchors means start and end of string, [1-9]{3} gives you exactly three non-zero digits, [AEIOU]{3} gives you exactly three vowels, and - gives you the literal separator character.
The "groups cannot be identical" rule is a little more problematic. I would just post process for that to ensure it's not violated. The following pseudo-code is what I mean:
def isValid(str):
if not str.regex_match("^[1-9]{3}-[AEIOU]{3}-[1-9]{3}-[AEIOU]{3}$"):
return false
return str[0..2] != str[8..10]
and str[4..6] != str[12..14]
The alternative will be a rather complex regex that future developers will probably curse you for inflicting on them :-)
Note that your "The groups of numbers may not contain zero" is a little ambiguous in that it may mean no zeros are allowed or just 000 is not allowed. I've assumed the former but it's easy adjustable to cater for the latter:
def isValid(str):
if not str.regex_match("^[0-9]{3}-[AEIOU]{3}-[0-9]{3}-[AEIOU]{3}$"):
return false
return str[0..2] != str[8..10]
and str[4..6] != str[12..14]
and str[0..2] != "000"
and str[8..10] != "000"
You can use capture group and backreferences
^([0-9]{3})-([AEIOU]{3})-(?:(?!\1)[0-9]){3}-(?:(?!\2)[AEIOU]){3}$
Regex Demo
The groups of numbers may not contain zero. From this if you meant only digits between 1 to 9 then you can replace [0-9] with [1-9]
If you don't want to have 000 then you can add a negative lookahead ^(?!.*000) to avoid matching 000
I want a very simple Regex for Javascript validation of phone number, which allows 10 digits and checks min numbers should be 10 and max 12 including - dash two times for ex. 123-123-1234
I have found some on internet, but none of them is working for min / max length.
Looking forward for quick response here.
Thanks !
You could do this
/^(?!.*-.*-.*-)(?=(?:\d{8,10}$)|(?:(?=.{9,11}$)[^-]*-[^-]*$)|(?:(?=.{10,12}$)[^-]*-[^-]*-[^-]*$) )[\d-]+$/
See it here on Regexr
(?!...) is a negative lookahead assertion
(?=...) is a positive lookahead assertion
^ # Start of the string
(?!.*-.*-.*-) # Fails if there are more than 2 dashes
(?=(?:\d{8,10}$) # if only digits to the end, then length 8 to 10
|(?:(?=.{9,11}$)[^-]*-[^-]*$) # if one dash, then length from 9 to 11
|(?:(?=.{10,12}$)
[^-]*-[^-]*-[^-]*$ # if two dashes, then length from 10 to 12
)
)
[\d-]+ # match digits and dashes (your rules are done by the assertions)
$ # the end of the string
What you asking for wouldn't be a simple regular expression and also may be solved without any use 'em.
function isPhoneNumberValid(number){
var parts, len = (
parts = /^\d[\d-]+\d$/g.test(number) && number.split('-'),
parts.length==3 && parts.join('').length
);
return (len>=10 && len<=12)
}
For sure this may be a bit slower than using a compiled regex, but overhead is way minor if you not going to check hundreds of thousandths phone numbers this way.
This isn't perfect in any way but may fit your needs, beware however that this allow two dashes in any place excluding start and end of number, so this will return true for string like 111--123123.
There's no simple way to do this with regexp, especially if you allow dashes to appear at some different points.
If you allow dashes only at places as in your example, then it would be ^\d{3}-?\d{3}-?\d{4}$
This one: ^[\d-]{10,12}$ matches string with length from 10 to 12 and contains only digits and dashes, but it also will match e.g. -1234567890-.