I can't seem to get a simple regular expression to work. Here's what I have at the moment:
$(".Hours").on('input', function (e) {
var regex = /^\d+(\.\d{0,2})?$/g;
if (!regex.test(this.value)) {
if (!regex.test(this.value[0]))
this.value = this.value.substring(1, this.value.length);
else
this.value = this.value.substring(0, this.value.length - 1);
}
});
I need the user to be able to only enter numbers and one decimal (with only two numbers after the decimal). It's working properly now, with the exception that a user cannot start with a decimal.
Acceptable:
23.53
0.43
1111.43
54335.34
235.23
.53 <--- Not working
Unacceptable:
0234.32 <--- The user can currently do this
23.453
1.343
.234.23
1.453.23
Any help on this?
Updated answer:
RegExp -
^(?:0|[1-9]\d+|)?(?:.?\d{0,2})?$
Explanation at regex101:
Original answer:
fiddle Demo
RegExp -
^(\d+)?([.]?\d{0,2})?$
Explanation
Assert position at the beginning of the string «^»
Match the regular expression below and capture its match into backreference number 1 «(\d+)?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match a single digit 0..9 «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the regular expression below and capture its match into backreference number 2 «([.]?\d{0,2})?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match the character “.” «[.]?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match a single digit 0..9 «\d{0,2}»
Between zero and 2 times, as many times as possible, giving back as needed (greedy) «{0,2}»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»
Here is a suggestion : /^((\d|[1-9]\d+)(\.\d{1,2})?|\.\d{1,2})$/.
Allows : 0, 0.00, 100, 100.1, 100.10, .1, .10...
Rejects : 01, 01.1, 100., .100, ....
Would this meet your needs:
var regex = /^\d+([.]?\d{0,2})?$/g;
Your regex:
var regex = /^\d+(\.\d{0,2})?$/g;
What you need:
var regex = /^\d*(\.\d{1,2})?$/;
You were requiring at least one digit before the decimal (\d+). I have also changed it so if you include a decimal, there must be at least one digit after it.
This one will force you to add digit after decimal separator :
^\d+([.]\d)?$
Example :
123 => true
=> false
123.1 => true
123.12 => false
123.. => false
if you want more digit; 3 for ex; make sure you fix min to "1" for digit after dicimal
^\d+([.]\d{1,3)?$
Related
I want a regex which returns true when there is at least 5 characters et 2 digits. For that, I use a the lookahead (i. e. (?=...)).
// this one works
let pwRegex = /(?=.{5,})(?=\D*\d{2})/;
let result = pwRegex.test("bana12");
console.log("result", result) // true
// this one won't
pwRegex = /(?=.{5,})(?=\d{2})/;
result = pwRegex.test("bana12");
console.log("result", result) // false
Why we need to add \D* to make it work ?
For me, \d{2} is looser than \D*\d{2} so it should not allow an acceptance of the test?
Your lookaheads only test from the current match position. Since you don't match anything, this means from the start. Since bana12 doesn't start with two digits, \d{2} fails. Its as simple as that ;)
Also, note that having \d{2} means your digits has to be adjacent. Is that your intention?
To simply require 2 digits, that doesn't need to be adjacent, try
/(?=.{5,})(?=\D*\d\D*\d)/
Note that lookaheads are zero-width assertions and when their patterns are matched the regex index stays at the same place where it has been before. The lookaheads in the patterns above are executed at the same locations.
The /(?=.{5,})(?=\d{2})/ pattern will match a location that has any 5 chars other than line break chars immediately to the right of the current location and the first 2 chars in this 5 char substring are digits.
You need to add \D* to let other types of chars before the 2 digits.
See more about that behavior at Lookarounds Stand their Ground.
I am trying to solve 'JavaScript Algorithms and Data Structures Projects: Telephone Number Validator' #freeCodeCamp.
I need to test if string contains 10 digits and what I've come up with returns false and I don't understand why.
console.log(/\d{10}/g.test("555-555-5555"))
If you want to do this with a single regular expression, you can use:
console.log(/^(?:\D*\d){10}\D*$/g.test("555-555-5555"))
console.log(/^(?:\D*\d){10}\D*$/g.test("555-555-55555"))
requiring the input to be composed of exactly 10 digits in addition to any number of other non-digit characters - but replacing non-digits with the empty string first would be a more intuitive and readable solution.
Here \d{10} means ten consecutive digits, not "ten digits with whatever in the middle, that's cool".
If want just 10 digits, you may want to strip non-digit data first:
let number = "555-555-5555";
// Remove all non-digit values (\D) which leaves only digits
let digits = number.replace(/\D/g, '').length;
It seems that your idea is correct, but this specific challenge has so many options for dashes [-] and parentheses [()] as inputs that there is a more efficient way to pass this.
function telephoneCheck(str) {
let phoneRegex = /^(1\s?)?(\d{3}|\(\d{3}\))[\s\-]?\d{3}[\s\-]?\d{4}$/
return phoneRegex.test(str);
}
The above is a way to complete the challenge in a single line of Regex, which can save you (or anyone else reading this in the future) a lot of time and space! Cheers
This is from an exercise on FCC beta and i can not understand how the following code means two consecutive numbers seeing how \D* means NOT 0 or more numbers and \d means number, so how does this accumulate to two numbers in a regexp?
let checkPass = /(?=\w{5,})(?=\D*\d)/;
This does not match two numbers. It doesn't really match anything except an empty string, as there is nothing preceding the lookup.
If you want to match two digits, you can do something like this:
(\d)(\d)
Or if you really want to do a positive lookup with the (?=\D*\d) section, you will have to do something like this:
\d(?=\D*\d)
This will match against the last digit which is followed by a bunch of non-digits and a single digit. A few examples (matched numbers highlighted):
2 hhebuehi3
^
245673
^^^^^
2v jugn45
^ ^
To also capture the second digit, you will have to put brackets around both numbers. Ie:
(\d)(?=\D*(\d))
Here it is in action.
In order to do what your original example wants, ie:
number
5+ \w characters
a non-number character
a number
... you will need to precede your original example with a \d character. This means that your lookups will actually match something which isn't just an empty string:
\d(?=\w{5,})(?=\D*\d)
IMPORTANT EDIT
After playing around a bit more with a JavaScript online console, I have worked out the problem with your original Regex.
This matches a string with 5 or more characters, including at least 1 number. This can match two numbers, but it can also match 1 number, 3 numbers, 12 numbers, etc. In order to match exactly two numbers in a string of 5-or-more characters, you should specify the number of digits you want in the second half of your lookup:
let regex = /(?=\w{5,})(?=\D*\d{2})/;
let string1 = "abcd2";
let regex1 = /(?=\w{5,})(?=\D*\d)/;
console.log("string 1 & regex 1: " + regex1.test(string1));
let regex2 = /(?=\w{5,})(?=\D*\d{2})/;
console.log("string 1 & regex 2: " + regex2.test(string1));
let string2 = "abcd23";
console.log("string 2 & regex 2: " + regex2.test(string2));
My original answer was about Regex in a vacuum and I glossed over the fact that you were using Regex in conjunction with JavaScript, which works a little differently when comparing Regex to a string. I still don't know why your original answer was supposed to match two numbers, but I hope this is a bit more helpful.
?= Positive lookahead
w{5,} matches any word character (equal to [a-zA-Z0-9_])
{5,}. matches between 5 and unlimited
\D* matches any character that\'s not a digit (equal to [^0-9])
* matches between zero and unlimited
\d matches a digit (equal to [0-9])
This expression is global - so tries to match all
You can always check your expression using regex101
I need your help as I'm stuck on a regular expression.
The regular expression needs to match any characters but the first number.
This first number can be an integer, negative, decimal.
so I have the RegExp for that:
var b = /[-]?[0-9]+([\.][0-9]+)?/;
but when I do that in JavaScript:
var a = 'ab123ab45',
b = /[-]?[0-9]+([\.][0-9]+)?/;
a.replace(b, '');
it obviously return: abab45
But what I need, as you may understood, is the other way around.
Here are some examples.
123 -> 123
123a -> 123
a123a -> 123
123ab45 -> 123
ab123ab45 -> 123
a1b2c3 -> 1
a1.2b -> 1.2
a1,2b -> 1
And I need to get that using only 1 regular expression with the replace function.
If you need it with replace (not with match):
var a = 'ab123ab45',
b = /.*?([-]?[0-9]+([\.][0-9]+)?).*/;
a.replace(b, '$1');
Try:
m = a.match(b);
console.log(m[0]);
Try this;
var a = "a1b2c3";
a = a.replace(/^.*?([.,\d]+).*?$/, "$1");
alert(a);
LIVE DEMO
Regex Explanation
^.*?([.,\d]+).*?$
Assert position at the beginning of the string «^»
Match any single character that is not a line break character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the regular expression below and capture its match into backreference number 1 «([.,\d]+)»
Match a single character present in the list below «[.,\d]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
One of the characters “.,” «.,»
A single digit 0..9 «\d»
Match any single character that is not a line break character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»
Could anyone tell me what RegEx would work to validate an international phone number including white space between the numbers and also allowing for these chars: - ( ).
The amount of numbers in the string is not too important, I would just like the user to be able to type something like either example 1 or 2 if they wish:
Example:
+44 (0) 207 111 1111
442071111111
I have already read through and tested the posted answers to some similar questions to the best of my understanding but so far none of them are working for me the way I want them to.
Please can someone help me out with a clear explanation of how the above should be written for validation?
Many thanks to anyone who can help.
Try this code
HTML Code
<input type="text" id="phone"/>
JS Code
$("#phone").blur(function() {
var regexp = /^[\s()+-]*([0-9][\s()+-]*){6,20}$/
var no = $("#phone").val();
if (!regexp.test(no) && no.length < 0) {
alert("Wrong phone no");
}
});
See A comprehensive regex for phone number validation
Quick cheat sheet
Start the expression: /^
If you want to require a space, use: [\s] or \s
If you want to require parenthesis, use: [(] and [)] . Using \( and \) is ugly and can make things confusing.
If you want anything to be optional, put a ? after it
If you want a hyphen, just type - or [-] . If you do not put it first or last in a series of other characters, though, you may need to escape it: \-
If you want to accept different choices in a slot, put brackets around the options: [-.\s] will require a hyphen, period, or space. A question mark after the last bracket will make all of those optional for that slot.
\d{3} : Requires a 3-digit number: 000-999. Shorthand for
[0-9][0-9][0-9].
[2-9] : Requires a digit 2-9 for that slot.
(\+|1\s)? : Accept a "plus" or a 1 and a space (pipe character, |, is "or"), and make it optional. The "plus" sign must be escaped.
If you want specific numbers to match a slot, enter them: [246] will require a 2, 4, or 6. [77|78] will require 77 or 78.
$/ : End the expression
This is a long regex, but it supports both formats (for example 2 to be a valid international number, is MUST start with either + or 00):
/^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$/i
This allows extensions and a multiple choice of formats and separators.
Matches:
(+351) 282 43 50 50
90191919908
555-8909
001 6867684
001 6867684x1
1 (234) 567-8901
1-234-567-8901 x1234
1-234-567-8901 ext1234
1-234 567.89/01 ext.1234
1(234)5678901x1234
(123)8575973
(0055)(123)8575973
On $n, it saves:
Country indicator
Phone number
Extention
This same answer was given here: A comprehensive regex for phone number validation (direct link to my answer)
/*
#isValidUSPhoneFormat function will check valid US Format
Allowed US Format
(123) 456-7890
123-456-7890
123.456.7890
1234567890
(734) 555.1212
*/
function isValidUSPhoneFormat(elementValue){
var phoneNumberPattern = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s.]{0,1}[0-9]{3}[-\s.]{0,1}[0-9]{4}$/;
if(phoneNumberPattern.test(elementValue) == false)
{
var phoneNumberPattern = /^(\()?\d{3}(\))?(.|\s)?\d{3}(.|\s)\d{4}$/;
return phoneNumberPattern.test(elementValue);
}
return phoneNumberPattern.test(elementValue);
}
May this will help you to understand JavaScript RegEx..
Don't even try. Trying to guard against what you think is invalid input can result in angry users who can't enter perfectly valid phone numbers. And if the user really wants to enter an invalid phone number, he/she will be able to do it anyway.
function checkPhoneNumber(val) {
var num = document.getElementById(val).value;
var mob=/^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g;
if (mob.test(num) == false) {
alert("Please Enter Valid Phone Number.");
document.getElementById(val).value = "";
return false;
}
if (num.length > 15) {
alert("Only 15 characters allowed for Phone Number field.");
document.getElementById(val).value = "";
return false;
}
return true;
}
Try it Ones
Try using isValidPhoneNumber(phoneNumber, countryCode) method of libphonenumber-js package. First is the phone number with "+" at the start of it. The second argument is the country code (for eg: 'US', 'IN'). That helps you validate any international number accurately.
Best lib for international phone number: google/libphonenumber
Here is an example with CDN:
<script src="https://cdn.jsdelivr.net/npm/google-libphonenumber#3/dist/libphonenumber.min.js"></script>
// Format Phone Number
function formatPhone(p) {
var phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();
var parsedPhone = phoneUtil.parse(p);
if (phoneUtil.isValidNumber(parsedPhone)) {
return phoneUtil.format(parsedPhone, libphonenumber.PhoneNumberFormat.INTERNATIONAL)
} else {
return NaN
}
}
A better option to validate international phone numbers in a loose way is as follows.This is not a strict validation
/^\s*(?:+?(\d{1,3}))?([-. (](\d{3})[-. )])?((\d{3})[-. ](\d{2,4})(?:[-.x ](\d+))?)\s*$/gm
A working Javascript function will look like this
function validatePhone(phone) {
var regex = /^\s*(?:\+?(\d{1,3}))?([-. (]*(\d{3})[-. )]*)?((\d{3})[-. ]*(\d{2,4})(?:[-.x ]*(\d+))?)\s*$/gm;
return regex.test(phone);
}
console.log(validatePhone('+973 11111111')) // true
console.log(validatePhone('+973 XX77yyss')) // false
For those who wish to have more about the characters:
^ asserts position at the start of a line
\s matches any whitespace character (equivalent to [\r\n\t\f\v ])
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Non-capturing group (?:+?(\d{1,3}))?
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
+ matches the character + with index 4310 (2B16 or 538) literally (case sensitive)
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy) 1st Capturing
Group (\d{1,3})
\d matches a digit (equivalent to [0-9])
{1,3} matches the previous token between 1 and 3 times, as many times as possible, giving back as needed (greedy) 2nd Capturing
Group ([-. (](\d{3})[-. )])?
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy) Match a single
character present in the list below [-. (]
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
-. ( matches a single character in the list -. ( (case sensitive) 3rd Capturing Group (\d{3})
\d matches a digit (equivalent to [0-9])
{3} matches the previous token exactly 3 times Match a single character present in the list below [-. )]
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
-. ) matches a single character in the list -. ) (case sensitive) 4th Capturing Group ((\d{3})[-. ](\d{2,4})(?:[-.x
](\d+))?) 5th Capturing Group (\d{3})
\d matches a digit (equivalent to [0-9])
{3} matches the previous token exactly 3 times Match a single character present in the list below [-. ]
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
-. matches a single character in the list -. (case sensitive) 6th Capturing Group (\d{2,4})
\d matches a digit (equivalent to [0-9])
{2,4} matches the previous token between 2 and 4 times, as many times as possible, giving back as needed (greedy) Non-capturing
group (?:[-.x ]*(\d+))?
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy) Match a single
character present in the list below [-.x ]
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
-.x matches a single character in the list -.x (case sensitive) 7th Capturing Group (\d+)
\d matches a digit (equivalent to [0-9])
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
\s matches any whitespace character (equivalent to [\r\n\t\f\v ])
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of a line
This would test positive for the below patterns and more
+42 555.123.4567 +1-(800)-123-4567 +7 555 1234567 +7(926)1234567 (926) 1234567 +79261234567 926 1234567 9261234567 1234567 123-4567 123-89-01 495 123