0

I've got a form with fields that are made visible based on some conditions (not relevant here). What happens is that I want to have validation on the fields based on their visibility.

So far, I haven't managed to change or disable a rule (such as required).

Here's an example:

<form>
 <input type='text' data-bind='{value : name}' />
 <span class='errorMsg' data-bind='validationMessage: name'></span>
 <input type='text' data-bind='{value : email, visible: isEmailVisible}' />
 <span class='errorMsg' data-bind='validationMessage: email'></span>
 <input type='checkbox' value='true' text='Receive an email' />
 <input type='submit' value='Send' />
</form>

In my js, I have a viewmodel with observable properties to control the visibility of the form's fields. When the checkbox is on, the email input is displayed and thus required. But when not checked, the validation rule should allow an empty email input.

so in my view model, I would have something like

self.email = ko.observable().extend({ required : {message : 'Should not be empty'}});

The question is : how to change or remove the validation rule ?

Thanks

Arnaud
  • 58
  • 5

1 Answers1

4

It appears that there is an onlyIf parameter that you can use with the validator:

ko.observable().extend({ required : {message : 'Should not be empty', 
    onlyIf: [viewModel.Observable bound to checkbox]}});
Paul Manzotti
  • 5,107
  • 21
  • 27