Hello Universe
Hello Universe

Reputation: 3302

How to validate input field phone with accurate Australian format using jQuery Validation?

I am trying to make an input (phone) field not required but validated according to Australian phone number.

        <div>
            <label for="contactPhone">Your Phone: </label>
            <input type="phone" class="form-control eform__phone"
                   id="contactPhone" name="phone"
                   placeholder="e.g. 04000000000">
        </div>

The JavaScript:

  /**
   * validate phone number according to australian format
   * Ref: https://ilikekillnerds.com/2014/08/regular-expression-for-validating-australian-phone-numbers-including-landline-and-mobile/
   */
  jQuery.validator.addMethod("phoneAU", function(value, element) {
    var phoneExpression = /^\({0,1}((0|\+61)(2|4|3|7|8)){0,1}\){0,1}(\ |-){0,1}[0-9]{2}(\ |-){0,1}[0-9]{2}(\ |-){0,1}[0-9]{1}(\ |-){0,1}[0-9]{3}$/;

    if (value.match(phoneExpression)) {
      return true;
    }
    return false;
  }, jQuery.validator.messages.phoneAU || "Please specify a valid phone number");

And then used the following in the validate rules function

   phone: {
     phoneAU: true
   },

I am using jQuery validation. However, it is considering as required. I do not want it to be required. I just want to make sure that whenever user fills it up, then they fill it up with the proper Australian format of phone number.

Upvotes: 0

Views: 408

Answers (2)

Sparky
Sparky

Reputation: 98738

The previously accepted answer is not the normal way to handle this situation. In order to preserve the ability to use a custom rule, while not making it mandatory, use "OR" this.optional(element) as part of the conditional, which is how the default rules in the plugin are constructed.

if (this.optional(element) || value.match(phoneExpression)) {
  return true;
}
return false;

or simply this single line shorthand version...

return this.optional(element) || value.match(phoneExpression);

Upvotes: 2

Jeto
Jeto

Reputation: 14927

Just change your "validated" condition to this:

if (value.length === 0 || value.match(phoneExpression)) {
  return true;
}

Edit: see @Sparky's answer for a more optimal/appropriate solution.

Upvotes: 1

Related Questions