formating UK mobile to international number with Zapier Code Javascript function - javascript

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}

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..

Remove a character in C#

System.FormatException: Input string was not in a correct format.
it is because the input expected should be numbers only but my input must be in the format of 555-555-5555 that is a requirement. here is my js to do so:
$(window).load(function () {
$("#phoneNumber").inputmask("***-***-****");
});
And here is my C# to render the value in this format (555)555-5555, the issue happens here
public static string phoneFormat(string phone)
{
//string[] splitNr = phone.Split('-');
// return ("(" + splitNr[0] + ")" + splitNr[1] + "-" + splitNr[2]);
string[] number = phone.Split();
return string.Format("{0:(###) ### - ####}",ulong.Parse(phone));//ERROR
}
if i use the commented out part it works but i want to use the parse way. How do i remove the "-" in C# after user input it in the UI and then display the number in this format (555)555-5555.
Thank you
It is easier to handle it as a string instead of trying to parse and then format it as number:
return Regex.Replace(phone, #"(\d{3})-(\d{3})-(\d{4})", "($1) $2 - $3")
For fun we can do this:
return string.Format("{0:(###) ### - ####}",ulong.Parse(phone.Replace("-", "")));
But what I'd really do is remove the input mask. Yes, use html/javascript to help the user put in good data, but do so in a way that's much more permissive. If I put in 5551234567, 555.123.4567, (555)123-4567, or even much worse, you should be able to handle any of those.
Input masks are usually bad UI/UX.
On the C# end, I'd really separate this into two parts: normalization, where I clean up potentially messy input for storage and validation, and formatting, where I take the normalized data and format it for display. The reason for two steps is because it's often much more efficient in terms of storage and indexing to store a basic (unformatted) value. Even better, sometimes users want to see the same data represented in different ways. Now it's easy for me to have different format options for the same value. Some people will also include validation as it's own phase, but I like to do this as part of normalizing the data.
Thus, for a really basic phone number, I'd handle the code like this:
public static string NormalizePhone(string phone)
{
// **We should give the user the benefit of the doubt.**
// I don't care what crazy format they used, if there are 10 digits, we can handle it.
//remove anything not a digit
var digits = Regex.Replace(phone, #"[^\d]", "");
//ensure exactly 10 characters remain
if (digits.Length != 10) throw new InvalidArgumentException($"{phone} is not a valid phone number in this system.");
return digits;
}
// Phone argument should be pre-normalized,
// because we want to be able to use this method with strings retrieved
// from storage without having to re-normalize them every time.
// Remember, you'll show a repeat value more often than you receive new values.
public static string FormatPhone(string phone)
{
//Even better if you have an Assert() here that can show phone is always pre-normalized in testing, but works to a no-op in production.
return Regex.Replace(phone, #"(\d{3})(\d{3})(\d{4})", "($1) $2 - $3");
}
Now your existing code can call them together:
try
{
FormatPhone(NormalizePhone(phone));
}
catch(InvalidArgumentException ex)
{
// This won't happen often.
// The html/js layer should stop it in most cases,
// such that we meet the rule of reserving exception handling for actual exceptional events.
// But you'll still want to add a meaningful handler here.
}
But really, I would call NormalizePhone() by itself, to have that raw value ready to save to the user's record, and then FormatPhone() afterwards, to show the user on the screen.
Finally, this is a simplistic port. Real phone number validation can be quite complicated. The link is pretty much the standard work in the area, and it's a whopping 12Mb of raw code.

How to format a phone number with .replace() function in 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.

Search string for numbers

I have a javascript chat bot where a person can type into an input box any question they like and hope to get an accurate answer. I can do this but I know I'm going about this all wrong because I don't know what position the number will appear in the sentence. If a person types in exactly:
what's the square root of 5 this works fine.
If he types in things like this it doesn't.
what is the square root of the 5
the square root of 5 is what
do you know what the square root of 5 is
etc
I need to be able to determine where the number appears in the sentence then do the calculation from there. Note the line below is part of a bigger working chatbot. In the line below I'm just trying to be able to answer any square root question regardless of where the number appears in the sentence. I also know there are many pitfalls with an open ended input box where a person can type anything such as spelling errors etc. This is just for entertainment not a serious scientific project. :)
if(
(word[0]=="what's") &&
(word[1]=="the") &&
(word[2]=="square") &&
(word[3]=="root") &&
(word [4]=="of") &&
(input.search(/\d{1,10}/)!=-1) &&
(num_of_words==6)
){
var root= word[5];
if(root<0){
document.result.result.value = "The square root of a negative number is not possible.";
}else{
word[5] = Math.sqrt(root);
word[5] = Math.round(word[5]*100)/100
document.result.result.value = "The square root of "+ root +" is "+ word[5] +".";
}
return true;
}
Just to be clear the bot is written using "If statemments" for a reason. If the input in this case doesn't include the words "what" and "square root" and "some number" the line doesn't trigger and is answered further down by the bot with a generic "I don't know type of response". So I'm hoping any answer will fit the format I am using. Be kind, I'm new here. I like making bots but I'm not much of a programmer. Thanks.
You can do this using a regular expression.
"What is the sqrt of 5?".match(/\d+/g);
["5"]
The output is an array containing all of the numbers found in the string. If you have more than one, like "Is the square root of 100 10?" then it will be
"Is the square root of 100 10?".match(/\d+/g);
["100", "10"]
so you can pick what number you want to use in your script.
You will need to use regular expressions, if you do not know what they are you should look them up as it would take too long to explain them in this response. Here is a useful website for regular expressions in JavaScript https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions.
Assuming that you know regular expressions you should first search for numbers and store all the numbers that you find, if no numbers are found print out an error message. As an added note, you may what to consider searching for mathematical constants such as pi or e. This should work
nums = someString./\d+|pi|e/gi
The next part is going to be hard but to boil it down to is core concept, you need to look for key words such as 'square root', 'times', or 'plus'. You should do this word by word going left to right. For example if a user inputs
What is 5 plus 3 minus 8?
you should detect the plus before the minus, while if this is inputted
What is 5 minus 3 plus 8?
You should detect the minus before the plus.
For operations that uses two numbers you need to take the first two numbers that you found and do the operation and replace the two numbers with the result. I am trying to use reverse polish notation if you do not quite understand what I am trying to do, look it up if do not know what it is.
I hope I understood your question correctly and provided some help to coming to a solution because what you asked is very hard but seems like fun. Good luck. Also as a warning I am not considering order of operations in my response.

Javascript percentage validation

I am after a regular expression that validates a percentage from 0 100 and allows two decimal places.
Does anyone know how to do this or know of good web site that has example of common regular expressions used for client side validation in javascript?
#Tom - Thanks for the questions. Ideally there would be no leading 0's or other trailing characters.
Thanks to all those who have replied so far. I have found the comments really interesting.
Rather than using regular expressions for this, I would simply convert the user's entered number to a floating point value, and then check for the range you want (0 to 100). Trying to do numeric range validation with regular expressions is almost always the wrong tool for the job.
var x = parseFloat(str);
if (isNaN(x) || x < 0 || x > 100) {
// value is out of range
}
I propose this one:
(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)
It matches 100, 100.0 and 100.00 using this part
^100(\.0{1,2})?$
and numbers like 0, 15, 99, 3.1, 21.67 using
^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$
Note what leading zeros are prohibited, but trailing zeros are allowed (though no more than two decimal places).
This reminds me of an old blog Entry By Alex Papadimoulis (of The Daily WTF fame) where he tells the following story:
"A client has asked me to build and install a custom shelving system. I'm at the point where I need to nail it, but I'm not sure what to use to pound the nails in. Should I use an old shoe or a glass bottle?"
How would you answer the question?
It depends. If you are looking to pound a small (20lb) nail in something like drywall, you'll find it much easier to use the bottle, especially if the shoe is dirty. However, if you are trying to drive a heavy nail into some wood, go with the shoe: the bottle with shatter in your hand.
There is something fundamentally wrong with the way you are building; you need to use real tools. Yes, it may involve a trip to the toolbox (or even to the hardware store), but doing it the right way is going to save a lot of time, money, and aggravation through the lifecycle of your product. You need to stop building things for money until you understand the basics of construction.
This is such a question where most people sees it as a challenge to come up with the correct regular expression to solve the problem, but it would be much better to just say that using regular expressions are using the wrong tool for the job.
The problem when trying to use regex to validate numeric ranges is that it is hard to change if the requirements for the allowed range is changes. Today the requirement may be to validate numbers between 0 and 100 and it is possible to write a regex for that which doesn't make your eyes bleed. But next week the requirment maybe changes so values between 0 and 315 are allowed. Good luck altering your regex.
The solution given by Greg Hewgill is probably better - even though it would validate "99fxx" as "99". But given the circumstances that might actually be ok.
Given that your value is in str
str.match(/^(100(\.0{1,2})?|([0-9]?[0-9](\.[0-9]{1,2})))$/)
^100(\.(0){0,2})?$|^([1-9]?[0-9])(\.(\d{0,2}))?\%$
This would match:
100.00
optional "1-9" followed by a digit (this makes the int part), optionally followed by a dot and two digits
From what I see, Greg Hewgill's example doesn't really work that well because parseFloat('15x') would simply return 15 which would match the 0<x<100 condition. Using parseFloat is clearly wrong because it doesn't validate the percentage value, it tries to force a validation. Some people around here are complaining about leading zeroes and some are ignoring trailing invalid characters. Maybe the author of the question should edit it and make clear what he needs.
I recomend this, if you are not exclusively developing for english speaking users:
[0-9]{1,2}((,|\.)[0-9]{1,10})?%?
You can simply replace the 10 by a 2 to get two decimal places.
My example will match:
15.5
5.4366%
1,43
50,55%
34
45%
Of cause the output of this one is harder to cast, but something like this will do (Java Code):
private static Double getMyVal(String myVal) {
if (myVal.contains("%")) {
myVal = myVal.replace("%", "");
}
if (myVal.contains(",")) {
myVal = myVal.replace(',', '.');
}
return Double.valueOf(myVal);
}
None of the above solutions worked for me, as I needed my regex to allow for values with numbers and a decimal while the user is typing ex: '18.'
This solution allows for an empty string so the user can delete their entire input, and accounts for the other rules articulated above.
/(^$)|(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)\.(\.[0-9]{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)/
(100|[0-9]{1,2})(\.[0-9]{1,2})?
That should be the regex you want. I suggest you to read Mastering Regular Expression and download RegexBuddy or The Regex Coach.
#mlarsen:
Is not that a regex here won't do the job better.
Remember that validation msut be done both on client and on server side, so something like:
100|(([1-9][0-9])|[0-9])(\.(([0-9][1-9])|[1-9]))?
would be a cross-language check, just beware of checking the input length with the output match length.
(100(\.(0){1,2})?|([1-9]{1}|[0-9]{2})(\.[0-9]{1,2})?)

Categories

Resources