Search code examples
knockout.jsknockout-validation

validate on submit not on focus lost


I'm using knockout validation plug-in. At the moment it triggers validation when a field loses its focus. Is there any way I can control when the validation should go off? Specifically, I want the validation to be triggered on form submit event, and don't want it on focus lost.


Solution

  • I think currently there is no way to stop validation on blur but we can do some workaround with the help of ValidationMessage binding. you can change configuration "insertMessages" to false so default validation message will not come then use ValidationMessage to show message and use one more flag which will be true on submit.

    Example Code:-

    ko.validation.configure({
     insertMessages: false
    });
    
    var vM = function () {
     this.isSubmit = ko.observable(false);
     this.Name = ko.observable().extend({
        required: true,
        number: true
     });
     this.errors = ko.validation.group(this);
    };
    vM.prototype.save = function () {
      this.isSubmit(true);
      if (!this.isValid()) {
         this.errors.showAllMessages();
      } else {
        alert("success");
      }
    };
    vM.prototype.set=function(){
      this.isSubmit(false);
    };
    ko.applyBindings(new vM());
    

    View:-

    Name:<input type="text" data-bind="value: Name,event: { keyup: set}" />
    <span data-bind="if: isSubmit">
      <p data-bind="validationMessage: Name"></p>
    </span>
    

    Fiddle Demo