How can I implement a live Javascript Regex for phone numbers? - javascript

I have a text box and it says "Phone:" as the standard here for phone number is (XXX)-XXX-XXXX
I'd like to have a javascript that automatically puts my numbers into that format if it's not in that format, so if you typed 9993334444 then it would change it automatically on the fly as I'm typing to (999)-333-4444 I have looked around Google for Javascript Phone Regex to no success, maybe a Regex isn't what I'm looking for?

you want to add an onkeyup event with a regex like
this.value = this.value.replace(/^\(?([0-9][0-9][0-9]){1}\)?-?([0-9][0-9][0-9][0-9]){1}-?([0-9][0-9][0-9]){1}$/, '($1)-$2-$3');
Check out http://jsfiddle.net/R8enX/
/ means start/end a regex string
^ means start of matching string
$ means end of matching string
? means 0 or 1 instances (make braces and dashes optional)
[0-9] means any single digit
(x){1} tags x as an expression that we can reference in the replacement with a $ sign
EDIT: realized I missed a digit on the last group of numbers, the jsfiddle will only work (properly) with 3 digits in the last group

To build somewhat on #Andrews answer you can check for a valid (local)phone number via this method. If the number is shorter or larger than 10 digits, it collapses back into an invalid number
-
<input type="text" onBlur="localNumber(this.value)"/>
<div id="output"></div>
-
<script>
var localNumber = function(str){
repl = str.replace(/^([0-9]{3})([0-9]{3})([0-9]{4})$/, "($1)-$2-$3");
outp = document.getElementById('output');
if( repl.match(/\W/) )
{
outp.innerHTML = repl;
}
else
{
outp.innerHTML = 'Invalid number for this region';
}
}
</script>

Related

Regex in Javascript - Need to allow decimal as first character

I have a React widget that lets you type in a price. I put the typed-in text through a regex.test() to ensure only numbers and 1 decimal are allowed in the number. However, the regex I'm using doesn't allow a decimal point as the first character (e.g. -> .05). My current regex is
`/^(\d+\.?\d{0,9}|\.\d{1,9})$/`
I tried adding an optional \.? in the front of this, but it didn't work. Thanks for your help!
You can use
/^\d*(?:\.\d+)?$/
const testFunc = (str) =>{
return str.length > 0 && /^\d*(?:\.\d+)?$/.test(str)
}
console.log(testFunc(''))
console.log(testFunc('.123'))
console.log(testFunc('1'))
console.log(testFunc('1.123'))
console.log(testFunc('123.123.123'))

Applying currency format using replace and a regular expression

I am trying to understand some code where a number is converted to a currency format. Thus, if you have 16.9 it converts to $16.90. The problem with the code is if you have an amount over $1,000, it just returns $1, an amount over $2,000 returns $2, etc. Amounts in the hundreds show up fine.
Here is the function:
var _formatCurrency = function(amount) {
return "$" + parseFloat(amount).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
};
(The reason the semicolon is after the bracket is because this function is in itself a statement in another function. That function is not relevant to this discussion.)
I found out that the person who originally put the code in there found it somewhere but didn't fully understand it and didn't test this particular scenario. I myself have not dealt much with regular expressions. I am not only trying to fix it, but to understand how it is working as it is now.
Here's what I've found out. The code between the backslash after the open parenthesis and the backslash before the g is the pattern. The g means global search. The \d means digit, and the (?=\d{3})+\. appears to mean find 3 digits plus a decimal point. I'm not sure I have that right, though, because if that was correct shouldn't it ignore numbers like 5.4? That works fine. Also, I'm not sure what the '$1,' is for. It looks to me like it is supposed to be placed where the digits are, but wouldn't that change all the numbers to $1? Also, why is there a comma after the 1?
Regarding your comment
I was hoping to just edit the regex so it would work properly.
The regex you are currently using is obviously not working for you so I think you should consider alternatives even if they are not too similar, and
Trying to keep the code change as small as possible
Understandable but sometimes it is better to use a code that is a little bit bigger and MORE READABLE than to go with compact and hieroglyphical.
Back to business:
I'm assuming you are getting a string as an argument and this string is composed only of digits and may or may not have a dot before the last 1 or 2 digts. Something like
//input //intended output
1 $1.00
20 $20.00
34.2 $34.20
23.1 $23.10
62516.16 $62,516.16
15.26 $15.26
4654656 $4,654,656.00
0.3 $0.30
I will let you do a pre-check of (assumed) non-valids like 1. | 2.2. | .6 | 4.8.1 | 4.856 | etc.
Proposed solution:
var _formatCurrency = function(amount) {
amount = "$" + amount.replace(/(\d)(?=(\d{3})+(\.(\d){0,2})*$)/g, '$1,');
if(amount.indexOf('.') === -1)
return amount + '.00';
var decimals = amount.split('.')[1];
return decimals.length < 2 ? amount + '0' : amount;
};
Regex break down:
(\d): Matches one digit. Parentheses group things for referencing when needed.
(?=(\d{3})+(\.(\d){0,2})*$). Now this guy. From end to beginning:
$: Matches the end of the string. This is what allows you to match from the end instead of the beginning which is very handy for adding the commas.
(\.(\d){0,2})*: This part processes the dot and decimals. The \. matches the dot. (\d){0,2} matches 0, 1 or 2 digits (the decimals). The * implies that this whole group can be empty.
?=(\d{3})+: \d{3} matches 3 digits exactly. + means at least one occurrence. Finally ?= matches a group after the main expression without including it in the result. In this case it takes three digits at a time (from the end remember?) and leaves them out of the result for when replacing.
g: Match and replace globally, the whole string.
Replacing with $1,: This is how captured groups are referenced for replacing, in this case the wanted group is number 1. Since the pattern will match every digit in the position 3n+1 (starting from the end or the dot) and catch it in the group number 1 ((\d)), then replacing that catch with $1, will effectively add a comma after each capture.
Try it and please feedback.
Also if you haven't already you should (and SO has not provided me with a format to stress this enough) really really look into this site as suggested by Taplar
The pattern is invalid, and your understanding of the function is incorrect. This function formats a number in a standard US currency, and here is how it works:
The parseFloat() function converts a string value to a decimal number.
The toFixed(2) function rounds the decimal number to 2 digits after the decimal point.
The replace() function is used here to add the thousands spearators (i.e. a comma after every 3 digits). The pattern is incorrect, so here is a suggested fix /(\d)(?=(\d{3})+\.)/g and this is how it works:
The (\d) captures a digit.
The (?=(\d{3})+\.) is called a look-ahead and it ensures that the captured digit above has one set of 3 digits (\d{3}) or more + followed by the decimal point \. after it followed by a decimal point.
The g flag/modifier is to apply the pattern globally, that is on the entire amount.
The replacement $1, replaces the pattern with the first captured group $1, which is in our case the digit (\d) (so technically replacing the digit with itself to make sure we don't lose the digit in the replacement) followed by a comma ,. So like I said, this is just to add the thousands separator.
Here are some tests with the suggested fix. Note that it works fine with numbers and strings:
var _formatCurrency = function(amount) {
return "$" + parseFloat(amount).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
};
console.log(_formatCurrency('1'));
console.log(_formatCurrency('100'));
console.log(_formatCurrency('1000'));
console.log(_formatCurrency('1000000.559'));
console.log(_formatCurrency('10000000000.559'));
console.log(_formatCurrency(1));
console.log(_formatCurrency(100));
console.log(_formatCurrency(1000));
console.log(_formatCurrency(1000000.559));
console.log(_formatCurrency(10000000000.559));
Okay, I want to apologize to everyone who answered. I did some further tracing and found out the JSON call which was bringing in the amount did in fact have a comma in it, so it is just parsing that first digit. I was looking in the wrong place in the code when I thought there was no comma in there already. I do appreciate everyone's input and hope you won't think too bad of me for not catching that before this whole exercise. If nothing else, at least I now know how that regex operates so I can make use of it in the future. Now I just have to go about removing that comma.
Have a great day!
Assuming that you are working with USD only, then this should work for you as an alternative to Regular Expressions. I have also included a few tests to verify that it is working properly.
var test1 = '16.9';
var test2 = '2000.5';
var test3 = '300000.23';
var test4 = '3000000.23';
function stringToUSD(inputString) {
const splitValues = inputString.split('.');
const wholeNumber = splitValues[0].split('')
.map(val => parseInt(val))
.reverse()
.map((val, idx, arr) => idx !== 0 && (idx + 1) % 3 === 0 && arr[idx + 1] !== undefined ? `,${val}` : val)
.reverse()
.join('');
return parseFloat(`${wholeNumber}.${splitValues[1]}`).toFixed(2);
}
console.log(stringToUSD(test1));
console.log(stringToUSD(test2));
console.log(stringToUSD(test3));
console.log(stringToUSD(test4));

jQuery - regex for integer and comma(s) - should only accept hundreds, thousands and millions

Max value should be 99,999,999 (no period at the end). So it should accept:
123
1,234
10,000
100,000
1,000,000
99,000,000
etc.
I found this code that does if perfectly for floats:
HTML
<input type="text" class="numberOnly" name="example" value="" required>
jQuery:
$('.numberOnly').keyup(function() {
var valid = /^\-?\d+\.\d*$|^\-?[\d]*$/;
var number = /\-\d+\.\d*|\-[\d]*|[\d]+\.[\d]*|[\d]+/;
if (!valid.test($(this).val())) {
var n = this.value.match(number);
this.value = n ? n[0] : '';
}
});
The values it accepts are: 1.1, .1, 1 (And they can even be negative values.)
Whenever a user types an invalid value, for example 1.., it automatically deletes the invalid value which in this case is the second dot.
I wanted to do something similar for my question. Here's what I have so far but obviously it's not working.
HTML:
<input type="text" class="millions" name="example2" value="" required>
jQuery:
$('.millions').keyup(function() {
var valid = /^(\d[0-0]{0,3}[\,]\d{0,9}[\,])?\d{0,9}$/;
var number = /\d{0,9}[\,](\d{0,9}[\,]\d{0,9})?/;
if (!valid.test($(this).val())) {
var n = this.value.match(number);
this.value = n ? n[0] : '';
}
});
In addition to wanting to know the correct regex format that I need, can anyone also explain what are valid and number variables used for?
Thank you so much!
The valid pattern is the one you're interested in for server side checking. It's the pattern used to check that the whole string conforms to your requirements. The number pattern is the one used to do replacement when the user types an illegal character. The number pattern needs to be more relaxed to allow the user to enter subsequences of valid patterns (e.g. 1,0) which the user may then complete to a valid pattern.
This pattern will do what you require:
var valid = /^([1-9]\d?(,\d{3}){0,2}|[1-9]\d{0,2}(,\d{3})?|0)$/;
Breaking it down:
^( - start of line
[1-9]\d{0,2} - first group starts with a non-zero digit followed by 0-1 digits
(,\d{3}){0,2} - 0-2 or comma separated groups of three digits
|[1-9]\d{0,2}(,\d{3})? - or a three digit leading group followed by a three digit trailing group
|0 - "0" by itself is valid
)$ - end of line
The number pattern is more complicated as it has to allow a trailing comma and allow groups of less than three digits at the end.

Auto correct phone format input

I'm trying to auto format an input on HTML with javascript, and it is almost done, i need the format to be xxx-xxx-xxxx but and I have this code
this.value = this.value.replace(/(\d{3})\-?/g,'$1-');
as youy can see it will just auto format xxx-xxx-xxx but I need to be 4 digits at the end
any sugestions?
Try this regexp:
'1234567890'.replace(/(\d{3}(?!\d?$))\-?/g, '$1-'); // 123-456-7890
The part (?!\d?$) is a negative lookahead. It allows regular expression to match three digits only if they are not followed by another number (4th) (but not necessarily ?) at the end of the string $.
So it will not match 789 group because it's followed by 0$.
Or simply : .replace(/(\d{3})(\d{3})(\d{4})\-?/g,'$1-$2-$3');
Sample code to help you out:
var phone = '(555) 666-7777';
// First clean your input
phone = phone.replace(/[^\d]/g, '');
// Check the length of the phone
if(phone.length == 10){
// Now we can format the phone
phone = phone.substring(0,3)+'-'+phone.substring(3,6)+'-'+phone.substring(6, 10);
// Optionally
//phone = phone.replace(/(\d{3})(\d{3})/, '$1-$2-');
}
else {
// whatever you want to tell the user
}
there seems to be a bug in the "replace" regex's above. enter a 10 digit number and you see it formatted correctly (e.g. "(123) 456-7890"). Then, select the contents of the field (double or triple click it) and overtype the value. You'll see the first two digits get transposed. So if you enter 1 2 3, you'll see 2 1 3...

mobile number validation using regex javascript

I want mobile number in format
+91(or any other country code)-9999999999(10 digit mobile number).
I have tried /^\+[0-9]{2,3}+[0-9]\d{10}, but its not working please help
Thanks in advance
Solution in short:
// should return an array with a single match representing the phone number in arr[0]
var arr = '+49-1234567890'.match(/^\+\d{1,3}-\d{9,10}$/);
// should return null
var nullVal = 'invalid entry'.match(/^\+\d{1,3}-\d{9,10}$/);
Longer explanation:
/ start regex
^ try to match from the beginning
\+ match a + sign
\d{1,3} match a digit 1 to 3 times
- match a dash
\d{9,10} match 9 or 10 digits
$ force the matching to be only valid if can be applied until string termination
/ finish regex
Knowing what the regex does, might let you modify it to your own needs
Sometimes it is good to ignore any whitespaces you come across. \s* matches 0 or n whitespaces. So in order to be more permissive you could let users input something like ' + 49 - 1232345 '
The regex to match this would be /^\s*\+\s*\d{1,3}\s*-\s*\d{9, 10}\s*$/ (just filled the possible space locations with \s*)
Other than that: I warmly recommend mastering regexes, because they come really handy in many situations.
If you are expecting a dash in the number (which your format shows), there is nothing in your regex to match it: is the second plus in the regex meant to be a dash?
^\+[0-9]{2,3}-[0-9]\d{10}
Also note that:
some country codes are single digit (eg. 1 for North America, 7 for Russia), these will not be matched
I doubt the local part of all mobiles everywhere is always 10 digits (eg. it won't be enough in countries with large populations as mobile ownership grows)
You can simply write the following:
var pattern=/^(0|[+91]{3})?[7-9][0-9]{9}$/;
\+[0-9]{2,3}-[0-9]+
Try this. This matches a + in the beginning, two or three numbers for the country code, followed by a - followed by any number of numbers
Use the mask function
jQuery(function($){
$("#phone").mask("999-999-9999",{placeholder:" "});
});
look here http://office.microsoft.com/en-in/access-help/control-data-entry-formats-with-input-masks-HA010096452.aspx
For mobile validation please try this
<html>
<head>
<title>Mobile number validation using regex</title>
<script type="text/javascript">
function validate() {
var mobile = document.getElementById("mobile").value;
var pattern = /^[7-9][0-9]{9}$/;
if (pattern.test(mobile)) {
alert("Your mobile number : "+mobile);
return true;
}
alert("It is not valid mobile number");
return false;
}
</script>
</head>
<body>
Enter Mobile No. :
<input type="text" name="mobile" id="mobile" />
<input type="submit" value="Check" onclick="validate();" />
</body>
</html>

Categories