regex for telephone number in validation form - django

in a django template with the html pattern tag and boostrap for form validation
with this regex it validates a sequence of numbers that can be separated by a dash
"^[+-]?\d(?:-?\d)+$"
example:
12-65-25-75-84 or 12-255-0214
the javascript :
(() => {
'use strict'
const forms = document.querySelectorAll('.needs-validation')
Array.from(forms).forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
and the html
<input type="text" class="form-control" id="exampleFormControlInput1" name="tel" id="tel" placeholder="Tel" pattern="^[+-]?\d(?:-?\d)+$" required>
</div>
I would like to know how to modify it to have the possibility of putting spaces between the numbers (in addition to the dashes)
example:
12 57 125-98-457
and limit the total number of digits to 15 (excluding spaces and dashes)
for example a string like this:
12-28-35-74-12
or
12 28 35 74 12
or
123-478 25 12 124-15
thank you

I would use:
^[0-9](?:[ -]?[0-9]){0,14}$
See RegEx Demo
^ - Matches the start of the string.
[0-9] - Matches a single digit (0, 1, ... 9).
(?: - Start of a non-capturing group.
[ -]? - Optionally matches either a space or '-'.
[0-9] - Matches a single digit (0, 1, ... 9).
) - End of the non-capturing group.
{0,14} - Maches the previous token, i.e. the previous non-capturing group, from 0 to 14 times.
$ - Matches the end of the string.

Related

How to match some specific one digit numbers or two digit numbers

I need to match either of these numbers in a capturing group: 1 2 4 8 16 32 64.
I tried: ([1248\b16\b\b32\b])(.*)$ that didn't work.
let RE = /([1248163264])/
let trues = ["q1", "q2", "q4", "q16", "q32", "q64"].forEach(_ => _.match(RE))
let falses = ["q3", "q13", "q6"].forEach(_ => _.match(RE))
console.log(trues, falses)
This pattern ([1248\b16\b\b32\b])(.*)$ has 2 capture groups, where the first capture group contains a character class that matches 1 of the listed characters.
If you meant to use a word boundary like (1248\b16\b\b32\b) then that would also not match as this is a pattern where all has to match in that order.
There is also no word boundary between 2 digits.
You might use negative lookarounds as digit boundaries instead:
(?<!\d)(?:[1248]|16|32|64)(?!\d)
Regex demo
let RE = /(?<!\d)(?:[1248]|16|32|64)(?!\d)/;
["q1", "q2", "q4", "q16", "q32", "q64"].forEach(s => console.log(`${s} --> ${RE.test(s)}`));
["q3", "q13", "q6"].forEach(s => console.log(`${s} --> ${RE.test(s)}`));

Regex to enter a decimal number digit by digit

I have a requirement where user can input only between 0.01 to 100.00 in a textbox. I am using regex to limit the data entered. However, I cannot enter a decimal point, like 95.83 in the regex. Can someone help me fix the below regex?
(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$
if I copy paste the value, it passes. But unable to type a decimal point.
Please advice.
Link to regex tester: https://regex101.com/r/b2BF6A/1
Link to demo: https://stackblitz.com/edit/react-9h2xsy
The regex
You can use the following regex:
See regex in use here
^(?:(?:\d?[1-9]|[1-9]0)(?:\.\d{0,2})?|0{0,2}\.(?:\d?[1-9]|[1-9]0)|10{2}(?:\.0{0,2})?)$
How it works
^(?:...|...|...)$ this anchors the pattern to ensure it matches the entire string
^ assert position at the start of the line
(?:...|...|...) non-capture group - used to group multiple alternations
$ assert position at the end of the line
(?:\d?[1-9]|[1-9]0)(?:\.\d{0,2})? first option
(?:\d?[1-9]|[1-9]0) match either of the following
\d?[1-9] optionally match any digit, then match a digit in the range of 1 to 9
[1-9]0 match any digit between 1 and 9, followed by 0
(?:\.\d{0,2})? optionally match the following
\. this character . literally
\d{0,2} match any digit between 0 and 2 times
0{0,2}\.(?:\d?[1-9]|[1-9]0) second option
0{0,2} match 0 between 0 and 2 times
\. match this character . literally
(?:\d?[1-9]|[1-9]0) match either of the following options
\d?[1-9] optionally match any digit, then match a digit in the range of 1 to 9
[1-9]0 match any digit between 1 and 9, followed by 0
10{2}(?:\.0{0,2})? third option
10{2} match 100
(?:\.0{0,2})? optionally match ., followed by 0 between 0 and 2 times
How it works (in simpler terms)
With the above descriptions for each alternation, this is what they will match:
Any two-digit number other than 0 or 00, optionally followed by any two-digit decimal.
In terms of a range, it's 1.00-99.99 with:
Optional leading zero: 01.00-99.99
Optional decimal: 01-99, or 01.-99, or 01.0-01.99
Any two-digit decimal other than 0 or 00
In terms of a range, it's .01-.99 with:
Optional leading zeroes: 00.01-00.99 or 0.01-0.99
Literally 100, followed by optional decimals: 100, or 100., or 100.0, or 100.00
The code
RegExp vs /pattern/
In your code, you can use either of the following options (replacing pattern with the pattern above):
new RegExp('pattern')
/pattern/
The first option above uses a string literal. This means that you must escape the backslash characters in the string in order for the pattern to be properly read:
^(?:(?:\\d?[1-9]|[1-9]0)(?:\\.\\d{0,2})?|0{0,2}\\.(?:\\d?[1-9]|[1-9]0)|10{2}(?:\\.0{0,2})?)$
The second option above allows you to avoid this and use the regex as is.
Here's a fork of your code using the second option.
Usability Issues
Please note that you'll run into a couple of usability issues with your current method of tackling this:
The user cannot erase all the digits they've entered. So if the user enters 100, they can only erase 00 and the 1 will remain. One option to resolving this is to make the entire non-capture group (with the alternations) optional by adding a ? after it. Whilst this does solve that issue, you now need to keep two regular expression patterns - one for user input and the other for validation. Alternatively, you could just test if the input is an empty string to allow it (but not validate the form until the field is filled.
The user cannot enter a number beginning with .. This is because we don't allow the input of . to go through your validation steps. The same rule applies here as the previous point made. You can allow it though if the value is . explicitly or add a new alternation of |\.
Similarly to my last point, you'll run into the issue for .0 when a user is trying to write something like .01. Again here, you can run the same test.
Similarly again, 0 is not valid input - same applies here.
An change to the regex that covers these states (0, ., .0, 0., 0.0, 00.0 - but not .00 alternatives) is:
^(?:(?:\d?[1-9]?|[1-9]0)(?:\.\d{0,2})?|0{0,2}\.(?:\d?[1-9]?|[1-9]0)|10{2}(?:\.0{0,2})?)$
Better would be to create logic for these cases to match them with a separate regex:
^0{0,2}\.?0?$
Usability Fixes
With the changes above in mind, your function would become:
See code fork here
handleChange(e) {
console.log(e.target.value)
const r1 = /^(?:(?:\d?[1-9]|[1-9]0)(?:\.\d{0,2})?|0{0,2}\.(?:\d?[1-9]|[1-9]0)|10{2}(?:\.0{0,2})?)$/;
const r2 = /^0{0,2}\.?0?$/
if (r1.test(e.target.value)) {
this.setState({
[e.target.name]: e.target.value
});
} else if (r2.test(e.target.value)) {
// Value is invalid, but permitted for usability purposes
this.setState({
[e.target.name]: e.target.value
});
}
}
This now allows the user to input those values, but also allows us to invalidate them if the user tries to submit it.
Using the range 0.01 to 100.00 without padding is this (non-factored):
0\.(?:0[1-9]|[1-9]\d)|[1-9]\d?\.\d{2}|100\.00
Expanded
# 0.01 to 0.99
0 \.
(?:
0 [1-9]
| [1-9] \d
)
|
# 1.00 to 99.99
[1-9] \d? \.
\d{2}
|
# 100.00
100 \.
00
It can be made to have an optional cascade if incremental partial form
should be allowed.
That partial is shown here for the top regex range :
^(?:0(?:\.(?:(?:0[1-9]?)|[1-9]\d?)?)?|[1-9]\d?(?:\.\d{0,2})?|1(?:0(?:0(?:\.0{0,2})?)?)?)?$
The code line with stringed regex :
const newRegExp = new RegExp("^(?:0(?:\\.(?:(?:0[1-9]?)|[1-9]\\d?)?)?|[1-9]\\d?(?:\\.\\d{0,2})?|1(?:0(?:0(?:\\.0{0,2})?)?)?)?$");
_________________________
The regex 'partial' above requires the input to be blank or to start
with a digit. It also doesn't allow 1-9 with a preceding 0.
If that is all to be allowed, a simple mod is this :
^(?:0{0,2}(?:\.(?:(?:0[1-9]?)|[1-9]\d?)?)?|(?:[1-9]\d?|0[1-9])(?:\.\d{0,2})?|1(?:0(?:0(?:\.0{0,2})?)?)?)?$
which allows input like the following:
(It should be noted that doing this requires allowing the dot . as
a valid input but could be converted to 0. on the fly to be put
inside the input box.)
.1
00.01
09.90
01.
01.11
00.1
00
.
Stringed version :
"^(?:0{0,2}(?:\\.(?:(?:0[1-9]?)|[1-9]\\d?)?)?|(?:[1-9]\\d?|0[1-9])(?:\\.\\d{0,2})?|1(?:0(?:0(?:\\.0{0,2})?)?)?)?$"

HTML5 Regular expression for pattern from 0 to 120 with interval of 5 and white space allowed?

I'm trying to get Regex fro HTML5 pattern attribute. My field should accept values from 0 to 120. There is interval of 5, so any value like 0,5,10,15,... 105,110,115,120 or they can enter or leave it blank. I'm wondering if there is a way to set the increment in REGEX? Here is my example:
<input type="text" name="fld1" id="fld1" value="" size="2" maxlength="3" pattern="[0-9]|[0-2]{1,3}" title="Integers from 0 to 120 with increment of 5 or leave it empty." />
Here's one way to do it:
<input type="number" min="0" max="120" step="5">
Use this Pattern \b([05]|\d[05]|1[01][05]|120)\b Demo
\b # <word boundary>
( # Capturing Group (1)
[05] # Character in [05] Character Class
| # OR
\d # <digit 0-9>
[05] # Character in [05] Character Class
| # OR
1 # "1"
[01] # Character in [01] Character Class
[05] # Character in [05] Character Class
| # OR
120 # "120"
) # End of Capturing Group (1)
\b # <word boundary>
Try this:
<input type='text' pattern='^(((\d|1[0-1])?(0|5)|120)|)$' />
REGEX isn't designed for numerical validation, but as you can see it can occasionally be possible with carefully-designed patterns.
That pattern says the beginning should be either any number (for numbers between 11 and 99) or 1 + either 1 or 0 (for numbers between 100-119), or neither. Most important, the final - or only - number should be a 0 or a 5.
Fiddle.
No increments that I am aware of. You can sort of make your own with a regex though:
^([05]|[1-9][05]|1[0-1][05]|120)$
Pretty much just having it say, you can have:
one number, 0 or 5
two numbers, first can be any non 0, then the second must be a 0 or 5
three numbers, first must be a 1, second 0 through 2, 3rd a 0 or a 5
The entire line must be like that. It can be adjust to allow leading or trailing white space if that is required. There will be several ways to write a regex like this, it just comes down to readability in my opinion. Good luck!

Django URL for 40 characters, Alphanumeric

I have try following URL:
url(r'^complete/(?P<id>\d+)/$', 'order_complete', name='checkout_complete'),
The ID I'm passing looks like this bupkrqpltfeqpctnnagjprzegq, which could be Max 40 characters.
How can I handle this?
I assume the image shows the allowed characters?
url(regex=r'^complete/(?P<id>[\w{}.-]{1,40})/$',
view='order_complete',
name='checkout_complete'),
Your pattern only allows digits (\d).
My pattern:
[\w{}.-] # a character that is a word character (a-zA-Z0-9 or _), {, }, ., or -
{1,40} # 1 to 40 times

Regex to match numbers 0-99.999

I need a regex that that matches numbers between 0 and 99.999 (99,999 is also valid).
Valid examples:
1,1
99.9
12.876
1,777
Invalid examples:
9837,83
-12,24
11.1112
^\d{1,2}(?:[.,]\d{1,3})?$
should do.
Explanation:
^ # anchor the match at the start of the string
\d{1,2} # match one or two digits
(?: # optionally match the following group:
[.,] # a . or ,
\d{1,3} # 1-3 digits
)? # end of optional group
$ # anchor the match the end of the string
If you are wanting to check a number is within a certain range you should not use Regex, it is too far removed from the logic of what you are doing and hard to debug. I would first replace commas with decimal points. Then check range.
eg (Javascript)
function isValid(inputString)
{
var number=parseFloat(inputString.replace(',','.'));
return (number>=0 && number <=99.999);
}
Updated Answer
The above solution does not account for the OP's requirement to have no more than 3 decimal places of precision.
function isValid(inputString){
var number=parseFloat(inputString.replace(',','.'));
validPrecision = true;
if (inputString.split('.')[1]) {
validPrecision=inputString.split('.')[1].length<=3;}
return (number>=0 && number <=99.999 && validPrecision);
};
Will this work ?
[0-9]{1,2}[.,][0-9]{1,3}
this matches stuff similar to this:
0.0 / 01,1
99,999 / 09.009
but not stuff like this:
.0 / ,1 / 1 / 01
099,999 / 09.0090
hope it helps.
The following will work:
^\d{1,2}((,|.)\d{1,3})?$