Hide Validation messages onLoad ? Knockout

2019-09-18 18:02发布

问题:

I been trying to hide error messages onload and i want them to display on save . i succeeded in many scenarios and i am able to adjust my code accordingly but this seems to be continious bug i am unable to get rid of it .

My function:

        function work() {
        var self=this;
        self.Time= ko.observable("");
        self.Validation = ko.validatedObservable([
                self.Time.extend({required:true}) ] );

        self.calculate=ko.computed(function(){
        return self.Time() * 2 ;
        });
  }

I added a Watch on this line self.mainArray.Validation.errors().length

As per my observation i debugged clearly to notice where the watch value getting incremented .

So i tried many ways to control the display of error message onLoad but it came to nothing like init , onlyif in extend etc

init i tried keep showmessages:false works one way but on save button click i can't further show messages

model.showerrormessages(false) does nothing

Working solution : Performance will get effected

ko.utils.arrayForEach(self.mainArray(), function (service) {
        if (service.Validation.errors().length > 0) {
            service.Validation.errors.showAllMessages(false);
        }

    });

Like this i have many loop inside loop structures i can't do same to everything and i just need something cool so i can hide messages onLoad .

I provided my observations any suggestion is quite handy here and if i can help you with more info please let me know.

回答1:

This will only compute the validation on submit, and includes showing error messages - http://codepen.io/dmoojunk/pen/zxqYbb

Html -

<div class="container no-padding">
    <div class="col-md-12 col-sm-12 col-xs-12">
        <div class="col-md-4 col-sm-4 col-xs-12">
            <div>
                <div>
                    <p>Phone: <a href="tel:0123456789">0123456789</a></p>
                    <p>Email: <a href="mailto:a@b.com" target="_top">email@example.co.uk</a></p>
                    <pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
                </div>
            </div>
        </div>

        <div class="col-md-8 col-sm-8 col-xs-12">
            <div>
                <div>
                    <form role="form">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group" data-bind="validationElement: firstName">
                                    <label class="control-label" for="contact-name">First Name</label>
                                    <input type="text" class="form-control" id="contact-name" placeholder="i.e Joe" data-bind="textInput: firstName"/>
                      <span class="help-block" data-bind="validationMessage: firstName"></span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group" data-bind="validationElement: email">
                                    <label class="control-label" for="contact-email">Email</label>
                                    <input type="email" class="form-control" id="contact-email" placeholder="i.e email@info.com" data-bind="textInput: email"/>
                      <span class="help-block" data-bind="validationMessage: email"></span>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group" data-bind="validationElement: surname">
                                    <label class="control-label" for="contact-surname"> Surname</label>
                                    <input type="text" class="form-control" id="contact-surname" placeholder="i.e Bloggs" data-bind="textInput: surname"/>
                      <span class="help-block" data-bind="validationMessage: surname"></span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group" data-bind="validationElement: category">
                                    <label class="control-label" for="contact-topic">Please select a category</label>
                                    <select class="form-control" id="contact-topic" data-bind="value: category">
                                        <option value="">Select category</option>
                                        <option value="general">General contact</option>
                                        <option value="issue">Report an issue</option>
                                        <option value="help">Help enquiry</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group" data-bind="validationElement: message">
                                <label class="control-label" for="contact-textarea">Write your message here, the more detail the better</label>
                              <textarea style="width:100%" id="contact-textarea" placeholder="Place message here" rows="10" data-bind="textInput:message"></textarea>
                   <span class="help-block" data-bind="validationMessage: message"></span>
                            </div>
                            <button type="button" class="btn btn-green" data-bind="click: submit">Get in touch</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

And JS -

var mynamespace = mynamespace || {};

ko.validation.init({
  errorElementClass: 'has-error',
  errorMessageClass: 'help-block',
  decorateElement: true,
  insertMessages: false
});

//Viewmodel
mynamespace.ContactUsViewModel = function(){
  var self = this;
  self.validationEnabled = ko.observable(false);
  self.isValidationEnabled = function() {
    return self.validationEnabled();
  }
  self.firstName = ko.observable('').extend({
    required: {
      onlyIf: self.isValidationEnabled
    },
    minLength: {
      onlyIf: self.isValidationEnabled,
      params: 5
    } 
  });
  self.email = ko.observable('').extend({
    required: {
      onlyIf: self.isValidationEnabled
    },
    email: {
      onlyIf: self.isValidationEnabled
    }
  });
  self.surname = ko.observable('').extend({
    required: {
      onlyIf: self.isValidationEnabled
    },
    minLength: {
      onlyIf: self.isValidationEnabled,
      params: 5
    } 
  });
  self.category = ko.observable('').extend({
    required: {
      onlyIf: self.isValidationEnabled
    },
    minLength: {
      onlyIf: self.isValidationEnabled,
      params: 1
    } 
  });
  self.message = ko.observable('').extend({
    required: {
      onlyIf: self.isValidationEnabled
    },
    minLength: {
      onlyIf: self.isValidationEnabled,
      params: 5
    } 
  });
  self.submit = function() {
    self.validationEnabled(true);
    if (!this.isValid()) {
      this.errors.showAllMessages();
    } else {
      alert('Form Valid');
    };
  }
};

var viewmodel = ko.validatedObservable(new mynamespace.ContactUsViewModel())();
ko.applyBindings(viewmodel);