Knockout验证插件 - 仅在表单提交时显示错误消息

时间:2014-06-19 07:43:01

标签: knockout.js knockout-validation

我正在使用敲除绑定以及敲除验证插件 (https://github.com/Knockout-Contrib/Knockout-Validation

我想仅在表单提交时显示错误消息,而不是在输入模糊,任何想法?

HTML

<div id="formErrorMessages" data-bind="visible: errors().length != 0">
           <p data-bind="validationMessage : email"></p>
           <p data-bind="validationMessage: firstName"></p>
           <span class="arrow-down"></span> </div>

<form id="short-reg-form" method="post" data-bind="validationOptions: { insertMessages:false,decorateInputElement:true,errorElementClass:'input-error' },submit:submit">   
    <input type="text" name="email" data-bind="value: email" class="email" data-placeholder="Email"/>   
    <input type="text" name="firstName" data-bind="value: firstName" class="right-input" data-placeholder="First Name"/>

</form>

JS

  

function viewModel(){

     

var self = this;

self.showErrorsDiv = ko.observable(false);
//Email
var emailPlaceholder = getPlaceholder("email");
self.email = ko.observable("")
    .extend({
        ng_required: {
            params: emailPlaceholder,
            message: notValidValueReturnString(emailString)
        },
        ng_email: {
            params:emailPlaceholder,
            message:notValidValueReturnString(emailString)
        }
    }).clearError(); // invoke clearError to prevent validation on page load.
//--Email
//FirstName
var firstNamePlaceholder = getPlaceholder("firstName");
self.firstName = ko.observable("").extend({
    ng_required: {
        params: firstNamePlaceholder,
        message : notValidValueReturnString(firstNameString)
    }
});
//--FirstName
self.submit = function (e) {

    if (self.errors().length == 0) { // check form validation.
        alert(true);
    } else {
        alert(false);
    }

    //prevent form submit default behavior.
    return false;
};

// utilities 
function getPlaceholder(nameAttributeVal) {
    return $('#short-reg-form input[name="' + nameAttributeVal + '"]').attr("data-placeholder");
}//--utilities  
     

}

$(function () {

// attach view model to the DOM
var pageModel = new viewModel();
pageModel.errors = ko.validation.group([pageModel.email,pageModel.firstName]);

ko.applyBindings(pageModel);
     

});

感谢。

3 个答案:

答案 0 :(得分:2)

我也有这个要求 - 客户并不希望用户看到红色&#39;在实际尝试提交表单之前。查看此代码集 - 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>

和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);

答案 1 :(得分:0)

试试这个:

var viewmodel = function () {
    var self = this;
    //...
    this.errors = ko.validation.group(this, { deep: true });

    this.submitViewModel = function () {
        if (self.errors().length > 0) {
            self.errors.showAllMessages(true);
            return;
        }
        //...
    }
}

答案 2 :(得分:0)

有一种方法可以实现,但是您需要使用init选项将insertMessages设置为false。

ko.validation.init({
    insertMessages: false,
    messagesOnModified: true,
    parseInputAttributes: false
});

应在加载validatedObservable或extend {required:true}等逻辑之前调用此代码。在加载任何viewModel代码之前,我在代码文件的顶部调用此代码。

接下来,您应该在视图模型中添加一个名为“ submitted”的新可观察对象。

var submitted = ko.observable(false);

现在,在“提交”按钮中单击,您可以执行以下操作:

var saveDraft = function () {
    submitted(true);
    var isValid = poll.isValid();
    if (!isValid) {
        console.log('not valid!');
        poll.errors.showAllMessages(true);
        return;
    }
}
model.saveDraft = saveDraft;

然后,您需要将验证消息手动放入标记中,如下所示:

    <div class="form-group">
        <div class="col-md-12">
            <label for="txtPollName" data-bind="">POLL NAME</label>
            <input type="text" class="form-control" id="txtPollName" placeholder="Enter a unique name for the poll." data-bind="value: poll().name">
            <div class="invalid-feedback" data-bind="visible: submitted(), validationMessage: poll().name">
            </div>
        </div>
    </div>

请注意,在标记中,我通过添加可见绑定来对ValidationMessage绑定进行了额外检查。因此,只有在提交表单后,才会显示验证消息。

也不要忘记,如果您的validatedObservable嵌套了需要验证的对象,则可以使用如下所示的分组实例化validatedObservable:

this.createPoll = function (parent, options) {
    var poll = new pollObject(parent, options);
    if (options && options.plain)
        return poll;
    var obs = ko.validatedObservable(null, { deep: true, live: true });
    obs(poll);
    return obs;
}

此代码段来自我的对象工厂,该工厂为我创建了我的对象并将其自动包装在分组的validatedObservables中。 deep:true选项表示isValid()将调用其所有子验证对象的isValid方法,并且所有对象都必须为true才能使对象有效。 Deep false表示仅对validatedObservable的值进行isValid检查,并且由于它始终具有值,因此它将始终有效。实时:true表示,如果实时对依赖的可观察对象进行了任何更改,则验证逻辑将重新运行。