Search code examples
regexknockout.jsphone-numberknockout-validation

allow comma in phone number


I would like to allow user to input comma in phone number field with Knockout Validation.

Is there any way to do this with Knockout? Currently I'm using validPhone to validate phone number like the code below:

this.PhoneNumber = ko.observable("").extend({
  required: { message: "Enter valid Phone Number" },
  validPhone: { message: 'Enter valid Phone Number' },
  maxLength: { params: 12, message: "Phone Number only allows 12 characters" }
});

Solution

  • You simply have to use the pattern validation, with a regular expression.

    Something like this:

    this.PhoneNumber = ko.observable("").extend({
      required: { message: "Enter valid Phone Number"},
      maxLength: { params: 12, message: "Phone Number only allows 12 characters" }
      pattern: {
        message: 'This isnt a valid phone number',
        params: '^ your phone no. regular expression here  $'
      }