How to format a phone number with .replace() function in Javascript - javascript

I am working on a regular expression for Canadian phone number in javascript and / or in jQuery. I'm having some trouble into the formating after I have passed my main regular expression.
Mainly, I need to format a phone number in this way when the user leave the input field :
111-222-3333
111-222-3333 #44444 (up to 5 digits)
1-222-333-4444
1-222-333-4444 #55555 (up to 5 digits)
As you can see above, I want to be able to format a normal phone number and a toll free number at the same time.
The code
In my HTML, I have done a simple input field.
<input id="assure_telephone" placeholder="Phone number" name="assure_telephone" maxlength="25" type="text" />
For my jQuery, I picked up the code found in my large file and simplified it a little bit. We need to focus on my regular expressions.
$('#assure_telephone').bind('change', function(){
// Delete all caracters and specials caraters except numbers
telephone_user = $('#assure_telephone').val().replace(/[^0-9]/g, '');
// Format the new phone number
telephone_user_regex = telephone_user.replace(/(\d{3})(\d{3})(\d{4})(\d{0,5})/, "$1-$2-$3 #$4");
$('#assure_telephone').val(telephone_user_regex);
});
The logic behind my code
As you can see, I'm starting by removing all special caracters to only keep numbers and then after I apply a formating with the .replace() Javscript function.
Link to my actual demo : http://jsfiddle.net/y201gcdg/6/
As you can see, it is pretty obvious that a toll free won't work as my formating is really made for normal phone number and not toll free.
My question is : Is there any way to work arround with the length of my telephone_user_regex variable to detect if it is a toll free or no OR is there any way to acheive it with a better regular expression?
Alternatively, I founded this on Stackoverflow that might be helping : https://code.google.com/p/libphonenumber/ (Source: Phone number format in Javascript)
Other ressource : http://www.w3schools.com/jsref/jsref_replace.asp
EDIT#1 - Deleted it after an answer that was not usefull.
EDIT#2 - Possible answer : Count the caracters
Source : A comprehensive regex for phone number validation
I could start with my first replace() function and then count the number of caracter, if it exceed X number, then apply a formating, else do an other one.
EDIT#3 - As I did not wanted to make an answer for my own question, I will post my workarround here.
var typephone = type;
// We take out all caracters except 0 to 9
var telephone_user = $('#'+typephone).val().replace(/[^0-9]/g, '');
// Now I can make switch case to detect the kind of phone number I need to format
switch(telephone_user.length) {
case 0 :
case 1 :
case 2 :
case 3 :
case 4 :
case 5 :
case 6 :
case 7 :
case 8 :
case 9 :
console.log('Your phone number is too small');
break;
case 10 :
console.log('This is a phone number 111-222-3333');
break;
}
In this way, I am able to detect the length and I could be able to know if it is a toll-free or a normal phone number. I might have trouble when it will come to the point the customer wrote something like this : 111-222-3333 #44444. After the special caracter removal, I won't be able to know if it was an extension.

Here's my suggestion:
Don't replace # (i.e. do replace(/[^0-9#]/g, '')), because otherwise you couldn't detect if the 11th character is the country code or an extension.
You can then use the position of the # to determine the length of the actual number (without extension), i.e., telephone_user.search("#")
You can then conditionally format the phone number based on #2, e.g. if it's the 12th digit, format telephone_user with the country code. Also, with the switch-case, I would just do the 3-4 valid cases, and default on everything else.

Related

nativeElement.value is NaN if there is a comma

I'm trying to set the number of decimals at 2 in an input. When I type a comma in it, the value becomes NaN so I would like get my number instead of this.
TS
#ViewChild('number') input;
limitNbOfDecimals() {
var regex =
this.form.number.search(/^(\d+(?:[\.\,]\d{0,2})?)$/) == 0
? true
: false;
if (regex == false) {
// Convert the value to a number
var nb: number = +this.input.nativeElement.value;
//set decimals at 2
this.input.nativeElement.value = nb.toFixed(2);
}
}
HTML
<input class="form-control" type="text" [(ngModel)]="form.number"
#number
name="number"
(input)="limitNbOfDecimals()"
/>
EDIT
I manage to add a comma in the number but if I try to add more than 2 decimals after it removes the numbers after the comma like 1,11 -> 1
This isn't a full answer, in the sense of having a total solution, but hopefully helps you get to one (and it's too long for a comment).
The spec at https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number) states:
This specification does not define what user interface user agents
are to use; user agent vendors are encouraged to consider what would
best serve their users' needs. ..... a user agent designed for the
French market might display the value with apostrophes between
thousands and commas before the decimals, and allow the user to enter
a value in that manner, internally converting it to the submission
format described above.
It would seem that the only sure way - if you don't have control over what browsers your users have - of ensuring they can type numbers in the format they are used to in their local setting is to take input as type text and on each keystroke check that they have typed something valid (as you have defined it) and when they submit it convert to a decimal number.
Searching provides code for doing this, depending on exactly what your requirement is for the number formats though you may be better off coding it from scratch.
To add more than 2 decimal values, you need to tell like .toFixed(4) etc..

Regex replace for commas in the thousands

I have a Javascript function I'm using to loop through a bunch of inputs on a page and convert them to a thousands-compatible comma system. In short, regardless of what the user types into the field, they'll get a friendly thousands-separated number back.
Input: 5000
Return: 5,000
Here's how the function breaks down
function add_commas()
{
$('.field-group .field input[type=text]').each(function()
{
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
}
Everything's working right except for one thing. Here's another example of the data being passed in and what's returned:
Input: 9.5
Return: 95
Note the whole number.
I'm wondering if there's a way to ignore or leave off the decimal if it didn't have one, but keep it and treat it respectfully if there is one. Here's the input/output as I would hope for:
Input: 5000
Return: 5,000
Input: 9.5
Return: 9.5
Input: 1000.50
Return: 1,000.50
Hopefully this was clear, but please do let me know if you require more information about the issue at hand. Thank you!
Actually regular expressions are not appropriate for this problem, because not every culture uses commas as thousands separators and periods for the radix separator. You should be using toLocaleString. In node, for example:
> (52342.214).toLocaleString()
'52,342.214'
> (52342.214).toLocaleString('de-DE')
'52.342,214'
> (52342.214).toLocaleString('ar-EG')
'٥٢٬٣٤٢٫٢١٤'
> (5234289877.21).toLocaleString('en-US')
'5,234,289,877.21'
This way you don't have to write your own error-prone code and you can localize for different cultures. The work has already been done for you!
You also get the zeros part of your question for free too! Notice:
> (38209).toLocaleString()
'38,209'
> (38209.0000).toLocaleString()
'38,209'
Again, all for free!
Change the first replace because it is removing the dot in the string
.replace(/[^0-9\.]/g, "")

formating UK mobile to international number with Zapier Code Javascript function

The scenario is...
A visitor comes to my landing page and completed the form, which included a telephone number.
Using Zapier I then pass that form data to ActiveCampaign.com using a "ZAP".
However as ActiveCampaign is in USA, they require the phone number formatting to international standard, instead of local UK.
Most numbers in UK are 07788990022
But it needs to be presented as +447788990022
So I need to use this built in function of Zapier listed below
https://zapier.com/help/code/
And need some Javascript code writing that will check the number
Is it valid UK mobile number? I.e. 11 digits
Remove all spaces, and trim
If 2nd character is a 7 then replace 1st character (which should be a 0) with +44
I really dont have any idea how to do this! I was hoping for a built in function on Zapier, but apparently not. Any ideas would be awesome!!!
David here, from the Zapier Platform team.
This seems like a pretty straightforward js question! This will be pretty "dumb" validation, but will work assuming the input is correct.
You'll have a code (javascript) step and set the input to be phone: input from step 1. Your code will look like this:
var ph = inputData.phone.replace(/\s+/g, '') // remove all whitespace from string
if (ph.length !== 11) {
// invalid phone number. do nothing?
return []
}
if (ph[1] === '7') {
ph = '+44' + ph.substr(1)
}
return {formattedNumber: ph}

Expression regular for check phone numbers at word level

I'm trying to write a RegEx to test if a number is valid and for valid I mean any number that matches country calling codes but also where the format of telephone numbers is standardized by ITU-T in the recommendation E.164. This specifies that the entire number should be 15 digits or shorter, and begin with a country prefix as said here so I did this:
^\+\d{2}|\d{3}([0-9])\d{7}$
But it's not working. In my case (VE numbers can't match the RegEx since this one are validated in another way) this input is valid:
+1420XXXXXXXXXXX // Slovakia - X is a digit and could be more, tough, 5 minimum
001420XXXXXXXXXX // Slovakia - I've changed from + to 00
420XXXXXXXXXXXXX // Slovakia - I've removed the 00 o + but number still being valid
+40XXXXXXXXXXXXX // Romania
Invalid numbers are the one that doesn't match the RegEx and the one started with +58 since they are from VE. So, resuming, a valid number should have:
+XX|+XXX plus 12|11 digits (5 minimum) where XX|XXX is the country code and then since maximum is 15 digits then should be 12 or 11 digits depending on the country format
Can any help me with this? It's a one I called complex
Few strange things going on with your regexp:
\d is shorthand for [0-9] - fine to use both, but I'm wondering why they're mixed
what you are searching with you OR (|) is "something that starts with +XX" i.e. plus and two numbers (^\+\d{2}) OR "something that ends with XXXXXXXXXXX" i.e. 11 numbers (\d{3}([0-9])\d{7}$)
You need to group (with brackets) the OR choices, otherwise it is everything to the left or everything to the right (simplistically)
^\+(\d{2}|\d{3})([0-9])\d{7}$
There is, however, another way of giving the number of occurrences : {m,n} means occurs between m and n times. So you could say ^\+\d{7,15}$ (where 7 is your minimum 5 + the minimum country code of 2).
To really do this, however, you might want to take a look here (https://code.google.com/p/libphonenumber/ 1) where there is a complete validation and formatting for all phone numbers available as javascript.

Phone ReGex to accept also letters after checking the first 3 or 4

I have found this awesome regex here in stack overflow and added the additional formats i need for my phone validation. But now I am asked to allow the following:
(555)YOU-RULE
(555) MEI-YOUN
(555)YOURULE
555YOURULE
555 YOU RULE
555-YOU-RULE
And all the above with the 1 before them. I am not sure how to do that given the solution I have below for none aphanumeric numbers
Only numeric:
var formats = "(999)999-9999|999-999-9999|(999) 999-9999|1(999) 999-9999|1(999)999-9999|999 999 9999|999.999.9999|1.999.999.9999|9999999999";
var r = RegExp("^(" +
formats
.replace(/([\(\)])/g, "\\$1")
.replace(/9/g,"\\d") +
")$");
phoneOK = r.test(phone);
There are better ways of doing this however less legible for those not intimately familiar with regex. So if you want to keep using this method, you should first understand what's going on here.
You are converting a custom syntax to regex and what you need to focus on is the 9 that you are converting to be any digit, you'll need to allow this to be any digit or letter.
This conversion is happening in line 5:
.replace(/9/g,"\\d") +
\d is the term for any digit so we'll have to make it mean any digit or letter. The easiest way to do this would likely be to change it to [\dA-Z]. I'm making the assumption here that you only want uppercase, if you also want lowercase change it to: [\dA-Za-z].
.replace(/9/g,"[\\dA-Z]") +
However, looking at your examples it looks like you also want only numbers in the first three digits. This will need a new rule. Let's call it 0 and update the formats accordingly:
var formats = "(000)999-9999|000-999-9999|(000) 999-9999|1(000) 999-9999|1(00)999-9999|000 999 9999|000.999.9999|1.000.999.9999|0009999999";
Now add the conversion after line 5:
.replace(/0/g,"\\d") +
You'll notice that it's the same as the old line 5.
So altogether we get:
var formats = "(000)999-9999|000-999-9999|(000) 999-9999|1(000) 999-9999|1(00)999-9999|000 999 9999|000.999.9999|1.000.999.9999|0009999999";
var r = RegExp("^(" +
formats
.replace(/([\(\)])/g, "\\$1")
.replace(/9/g,"[\\dA-Z]")
.replace(/0/g,"\\d") +
")$");
phoneOK = r.test(phone);

Categories

Resources