敲除自定义验证:如何检查可观察值是否等于特定值?

时间:2019-02-11 22:28:37

标签: javascript knockout.js knockout-validation

我是Knockout.js的新手,我想检查表单中的字段是否具有特定值。实际上,我只检查是否需要。我该怎么办?

这是我的html页面中的内容:

 <div data-bind="visible: !Vm.isValid()" class="text-danger">Fill each field to send data, otherwise show this message</div>

 <input data-bind="enable: Vm.isValid()" type="button" value="Send data!" />

这就是我的vm.js文件的样子:

 window.Vm = ko.validatedObservable({
     name : ko.observable().extend({ required: true })
 });            

我会做这样的事情,但是我不知道该怎么做:

 var found = "found";
 window.Vm = ko.validatedObservable({
    name: ko.observable().extend({
       required: true,
       function: {
          if (this.val() == found)
             return true; // invalid value, can't submit my form
       }
    })
 });

3 个答案:

答案 0 :(得分:0)

您可以像这样(Documentation)使用自定义validator

var found = "found";

var Vm = ko.validatedObservable({
  name: ko.observable().extend({
    required: {
      message: "This is a required field",
    },
    validation: {
      validator: (val, paramValue) => {
        // "val" has the value entered in the field
        // "paramValue" has the value set in "params"
        return val === paramValue
      },
      message: "The value is not " + found,
      params: found
    }
  })
});

ko.applyBindings(Vm)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>

<input type="text" data-bind="value: name" />

答案 1 :(得分:0)

我实际上建议不要使用Knockout Validation库,因为它已经多年没有维护了。对于已经不再存在的问题,这是一个过时的解决方案。在2019年,您可以使用每个现代浏览器都固有的表单验证。只需在表单字段上放置一个required属性,如果未填写所有必填字段,表单将不会提交。

如果您希望它更具动态性,可以执行以下操作:

function ViewModel() {
    var vm = this;

    vm.name = ko.observable();
    vm.required = ['name', 'email'];

    vm.isRequired = isRequired;

    function isRequired(field) {
        return vm.required.indexOf(field) > -1;
    }
}

并使用attr绑定根据视图模型中所需元素的数组设置required属性。

<input type="text" data-bind="textInput: name, attr: { required: isRequired('name') }">

答案 2 :(得分:0)

  

我将数据取为[“ A”,“ B”],并根据相同的数据进行搜索。

ko.extenders.required = function(target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();
    target.data = ko.observableArray(["A","B"]);
 		target.found = ko.observable();
    target.foundMessage = ko.observable();
    //define a function to do validation
    function validate(newValue) {
       target.hasError(newValue ? false : true);
       target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
       target.found(target.data().find(function(element){ return newValue==element;}));
       target.found()?target.foundMessage("element has found"):target.foundMessage("element has not found");
    }
 
    //initial validation
    validate(target());
 
    //validate whenever the value changes
    target.subscribe(validate);
 
    //return the original observable
    return target;
};
 
function AppViewModel(first) {
    this.firstName = ko.observable(first).extend({ required: "" });
}
 
ko.applyBindings(new AppViewModel("C"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
<p data-bind="css: { error: firstName.hasError }">
    <input data-bind='value: firstName, valueUpdate: "afterkeydown"' />
    <span data-bind='visible: firstName.hasError, text: firstName.validationMessage'> </span>
    <span data-bind='visible: (!firstName.hasError()), text: firstName.foundMessage'> </span>
</p>