Format a US Phone Numner


/ Published in: JavaScript
Save to your folder(s)

Generic function - Pass the context to the function for use with any field


Copy this code and paste it in your HTML
  1. function FormatPhoneNumber(eContext)
  2. {
  3. // Get the field that fired the event.
  4. var oField = eContext.getEventSource().getValue();
  5. var sTmp = oField
  6.  
  7. // Validate the field information.
  8. if (typeof(oField) != "undefined" && oField != null)
  9. {
  10. // Remove any non-numeric characters.
  11. var sTmp = oField.replace(/[^0-9]/g, "");
  12.  
  13. // If the number has a valid length, format the number.
  14. switch (sTmp.length)
  15. {
  16. case "4105551212".length:
  17. oField = "(" + sTmp.substr(0, 3) + ") " +
  18. sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4);
  19. break;
  20.  
  21. case "5551212".length:
  22. oField.DataValue = sTmp.substr(0, 3) + "-" +
  23. sTmp.substr(3, 4);
  24. break;
  25. }
  26. }
  27. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.