US Phone number validation - Jquery


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

Validating phone number using jquery


Copy this code and paste it in your HTML
  1. jquery.usphone.js
  2. ===============================================================
  3.  
  4. (function( $ )
  5. {
  6. // This function formats a text field to a US
  7. // phone number as the user types the information.
  8.  
  9. $.fn.usphone = function()
  10. {
  11. this.keyup(function()
  12. {
  13. var curchrindex = this.value.length;
  14. var curval = $(this).val();
  15. var strvalidchars = "0123456789()-";
  16.  
  17. for (i =0; i < this.value.length; i++)
  18. {
  19. var curchar = curval[i];
  20. if (strvalidchars.indexOf(curchar) == -1)
  21. {
  22. //delete the character typed if this is not a valid character.
  23. $(this).val(curval.substring(0, i) + curval.substring(i+1, this.value.length));
  24. }
  25. }
  26.  
  27. // Insert formatting at the right places
  28. if (curchrindex == 3)
  29. {
  30. $(this).val("(" + curval + ")" + "-");
  31. }
  32. else if (curchrindex == 9)
  33. {
  34. $(this).val(curval + "-");
  35. }
  36.  
  37. //Do not allow more than 15 characters including the brackets and the "-"
  38. if (curchrindex == 15)
  39. {
  40. //delete the last character typed
  41. $(this).val(curval.substring(0, this.value.length-1 ));
  42. }
  43.  
  44. });
  45. };
  46. })( jQuery );
  47.  
  48. --- Script Code Below ----------
  49.  
  50. <script>
  51. $('#phonenumber').usphone();
  52. </script>

URL: http://nsreekanth.blogspot.in/2010/12/simple-jquery-plugin-to-validate-format.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.