Skip to content

Instantly share code, notes, and snippets.

@Rio517
Created January 10, 2012 22:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Rio517/1591694 to your computer and use it in GitHub Desktop.
Save Rio517/1591694 to your computer and use it in GitHub Desktop.
Add method to Jquery Validate for Phone Numbers
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
// Source: http://docs.jquery.com/Plugins/Validation/CustomMethods/phoneUS
@logicerpsolution
Copy link

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"> </script> <script type="text/javascript"> $(document).ready(function () { $("#btnValidate").click(function () { var phoneText = $("#txtPhone").val(); if ($.trim(phoneText).length == 0) { alert("Please enter Phone Number"); return false; } if (validatePhone(phoneText)) { alert('Valid Phone Number'); return true; } else { alert('Invalid Phone Number'); return false; } }); }); function validatePhone(phoneText) { var filter = /^[0-9-+]+$/; if (filter.test(phoneText)) { return true; } else { return false; } } </script>

<asp:TextBox ID="txtPhone" runat="server" />
<asp:Button ID="btnValidate" runat="server" Text="Validate" />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment