0

I am trying to add validation for a phone number,

I need it to be required however I only want the pattern enforced if the country is the US This is what I have but it fails when I have Canada or any other country chosen

self.phone = ko.observable().extend({
        required: {
            onlyIf: function () {
                return self.country() == "US";
            }
        },

        pattern: {
            message: 'Please enter a valid phone number in ###-###-#### format',
            params: /^(\d{3}-\d{3}-\d{4})$/
        }
    });
China Syndrome
  • 953
  • 12
  • 24

1 Answers1

3

very simple. just add the same onlyIf condition to pattern validator

function ViewModel() {
  var self = this;
  self.country = ko.observable();
  self.phone = ko.observable().extend({
    required: true,

    pattern: {
      message: 'Please enter a valid phone number in ###-###-#### format',
      params: /^(\d{3}-\d{3}-\d{4})$/,
      onlyIf: function() {
        return self.country() == "US";
      }
    }
  });
  
  self.errors = ko.validation.group(self);
  
  self.isValid = function() { self.errors.showAllMessages() }
  self.clear = function() { self.errors.showAllMessages(false) }
}

ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>
Country <input data-bind="textInput: country"><br><br>
Phone <input data-bind="textInput: phone"><br><br>
<button data-bind="click: isValid">Show Errors</button>
<button data-bind="click: clear">Clear</button>
Ja9ad335h
  • 4,995
  • 2
  • 21
  • 29