jQuery Validate phone method

Adds method to jquery validate for checking a specific phone number format

by Preston Badeer

HTML

<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<form id="form" method="post">
    <input type="text" name="phone" class="phone" value="123-456-7891" />
    <input type="submit" />
</form>
<div></div>

JavaScript

$.validator.addMethod("phoneVal", function (number, element) {
    number = number.replace(/\s+/g, "");
    if (number.length == 12 && number.match(/^([0-9]{3})\-([0-9]{3})\-([0-9]{4})$/)) return true;
    else return false;
}, "Please specify a valid phone number");
/*
^([0-9]{3})\-([0-9]{3})\-([0-9]{4})$
^        # Assert position at the beginning of the string.
\(       # Match a literal "("...
  ?      #   between zero and one time.
(        # Capture the enclosed match to backreference 1...
  [0-9]  #   Match a digit...
    {3}  #     exactly three times.
)        # End capturing group 1.
\)       # Match a literal ")"...
  ?      #   between zero and one time.
[-. ]    # Match one character from the set "-. "...
  ?      #   between zero and one time.
⋯        # [Match the remaining digits and separator.]
$        # Assert position at the end of the string.
*/

$('#form').validate({
    rules: {
        phone: {
            phoneVal: true
        }
    },
    submitHandler: function () {
        $('div').text('done');
    },
    invalidHandler: function () {
        $('div').text('not');
    }
});