Pregunta

I check my view model on submit for validation as described here on SO, actually.

My form has a "Save Progress" action in addition to the "Submit" action. It submits to the server in much the same way, but has fewer required fields.

I would like to keep the four absolutely required fields where they currently are in the View Model ... i.e. keep them in the larger validation group for submission.

Is there a way in Knockout Validation to simply show specific messages in the same way as showAllMessages() would for the full validation group? I have looked through the source, but couldn't find anything like showMessage() attached to a single error.

Or, is there a way to pick and choose fields from my View Model and put them in their own validation group (but keep them in the larger group as well)?

So, as an example:

var ViewModel = ko.validatedObservable({
  requiredForSave1:  ko.observable().extend({ required: true }),
  requiredForSave2:  ko.observable().extend({ required: true }),
  requiredForSubmit: ko.observable().extend({ required: true })
  // ... and many more.
});

$('#sumbit').on('click', function(){

  //check the entire validation group
  if ( ViewModel.errors().length === 0 ){
    doSubmit();
  }
  else{
    ViewModel.errors.showAllMessages();
  }
});

$('#save').on('click', function(){

  //check only part of the validation group
  if ( ViewModel.requiredForSave1.isValid() &&
       ViewModel.requiredForSave2.isValid() ){

    doSubmit();
  }
  else{
     //show only one or two specific validation messages.
     //???
  }

});

Is there a way to fill in that last else block, or should I be taking a different approach to this?

Thanks

¿Fue útil?

Solución

Or, is there a way to pick and choose fields from my View Model and put them in their own validation group (but keep them in the larger group as well)?

Yes, you can define as many groups as you want; and observables can be in multiple validation groups.

So, for example, let's say your validation group for all of the errors in your view model is the following:

ViewModel.errors = ko.validation.group(ViewModel);

You can also add individual groups like this:

ViewModel.saveErrors = ko.validation.group([ViewModel.requiredForSave1, ViewModel.requiredForSave2]);

Also, by calling showAllMessages on a validation group you are only showing the messages for the observables within that group. ViewModel.saveErrors.showAllMessages() will only show the validation messages for requiredForSave1 and requiredForSave2

Hope that helps

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top