Great community here!
I am currently working within a 2011 CRM system that has a new requirement of the end users updating Contact Addresses from domestic (US) addressing to International. The system was originally set up for just Domestic addresses.
My problems are with the Telephone field and zip code. Both have custom javascript to format the integers in the field and ensure length compliance.
Now, is it possible to manipulate the JavaScript below to handle the both domestic and international phone numbers?
Below is the function that is called on an onchange event:
function checkPhoneNumberFormat(obj) {
var phoneNumber = obj.getEventSource().getValue();
if (phoneNumber != null) {
var sTmp = phoneNumber.replace(/[^0-9]/g, "");
switch (sTmp.length) {
case 10:
obj.getEventSource().setValue("(" + sTmp.substr(0, 3) + ") " + sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4));
break;
default:
alert("Phone must contain 10 numbers.");
break;
}
}
}
Somewhat new to java scripting, just looking for some feed back, on how to manipulate this code. It would be great if it had the ability to auto format 9 digit as well as 14 digit phone numbers. And only allow numbers of those lengths to be passed through on the save.
Any comments or ideas are greatly appreciated.
Thank You!
Yes Pawel, this is pretty simple to do:
put another case statement like this (this means do nothing, but don't throw that alert up when the length is 14, since you don't want to do any special formatting)
case 14:
break;
Then in your onsave - you can do the same thing but block saving in the "Default" case.
default:
alert("Phone number must contain 10 or 14 digits");
executionObj.getEventArgs().preventDefault();
break;
One thing to note about phone numbers is that often there can be extensions, this doesn't seem to be handled by your code, but maybe that is not relevant to your application.
Related
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..
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.
I have a piece of JavaScript code that keeps throwing an 'Is Undefined' error.
< script language = "javascript"
type = "text/javascript" >
// fuction added for click on submit - dp0jmr 05/23/2018
function checkScheduleAndAmount() {
var ppAmt = (double)
<%=p.getPaymentPlanAmt()%>;
var totalamt = (double) document.getElementById("sum").innerText;
if (ppAmt != totalamt) {
alert("The Payment Plan Schedule does not add up to the total Payment Plan Amount - this Payment Plan cannot be submitted." +
" Please correct the Amounts entered and submit the Payment Plan Schedule before leaving this page." +
"\n\nIf the Date Range you have entered does not allow you to enter the Plan you desire, please End this Payment Plan " +
"and begin a new one." +
"\n\nIf you know the installment amount you wish to use, you can enter an installment amount at the start of a new " +
"Payment Plan, and the application will calculate the final payoff date for you. ");
return false;
} else {
return true;
}
}
<
/script>
I've eliminated as many possible culprits as I could:
I've tried every combination of script definitions - there is some JQuery in addition to this JavaScript, but it was running fine alongside it until recently.
I tried putting it inside the page element with no effect.
I don't see any obvious syntax errors - all the variables being used here are defined.
The function call is on an html:button tag, at the very bottom of the div.
<html:submit property="submitValue" value="<%=PaymentPlanDetailsForm.SUBMIT%>" styleClass="button" disabled="<%=isActive %>" onclick="return checkScheduleAndAmount()" onkeypress="return false"/>
This started to occur recently after refining my JQuery function, but both functions seemed to be working fine during testing, and even seemed to work without issue together for awhile - and unfortunately, I cannot revert my changes now because I made the mistake of closing the IDE. :(
Am I missing something obvious in the syntax for this? Or is there another reason my page isn't recognizing my javascript function?
This JavaScript code:
var totalamt = (double) document.getElementById("sum").innerText;
...is invalid JavaScript code, and so the parsing fails, and the function isn't created.
JavaScript is not C# or Java or (insert language here). It doesn't have casting. Just remove the (double) part. If you want to convert that string to a number, use a unary +, the Number function, parseInt, or parseFloat.
For instance, if you want to convert all of the text to a number, and treat a blank as an invalid input, then:
var str = document.getElementById("sum").innerText;
var totalamt = str ? +str : NaN;
if (isNaN(totalamt)) {
// ...it wasn't a valid number
}
As I mentioned, you could also use parseInt or parseFloat, but beware that they accept numbers with trailing non-numeric characters (parseFloat("123.4abc") is 123.4, for instance).
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}
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.