嵌套视图模型中的knockout.ja验证错误

时间:2015-09-28 09:39:00

标签: javascript mvvm knockout.js knockout-validation

我在使用knockout.js验证插件时遇到问题。当我尝试在newPerson viewmodel中定义'errors'时,编译器说newPerson是未定义的。总的来说,使用视图模型的对象类型而不是函数类型进行敲除验证是否正确?

var clientModel = {

  newPerson: {
    EmailAddress: ko.observable().extend({
      required: {
        params: true,
        message: "This field is required"
      },
      emailFormatCheck: {
        params: true,
        message: ""
      }
    }),
    errors: ko.validation.group(newPerson, {
      deep: true
    })
  }

}


ko.extenders.emailFormatCheck = function(target, overrideMessage) {

  target.hasError = ko.observable();
  target.validationMessage = ko.observable();

  function validate(newValue) {
    var matches = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i.exec(newValue);
    if (matches == null) {
      target.hasError(true);
      target.validationMessage("The email format is wrong!!!");

    } else {
      target.hasError(false);
    }
  }
  validate(target());
  target.subscribe(validate);
  return target;
};

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

ko.applyBindings();
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<div class="panel panel-primary">
  <div class="panel-heading"></div>
  <div class="panel-body">
    <form role="form" data-bind="with: clientMode.newPerson">
      <div class="form-group">
        <p data-bind="css: { error: EmailAddress.hasError }">
          <label>Email</label>
          <br />
          <input class="form-control" data-bind="value: EmailAddress, valueUpdate: 'afterkeydown'" /> <span data-bind="visible:  EmailAddress.hasError, text: EmailAddress.validationMessage"> </span>

        </p>
      </div>
      <br />
    </form>
  </div>
  <div class="panel-footer">
    <button type="submit" class="btn btn-default" data-bind=" enable:!clientModel.errors().length">Creat</button>
  </div>
</div>

提前谢谢

0 个答案:

没有答案