最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Multiple "pattern" validation extenders using knockout - Stack Overflow

programmeradmin3浏览0评论

If I extend a knockout observable like so

var x = ko.observable().
extend({ 
     pattern : { 
         params: someRegex,
         message: "An error"
    }
})
.extend({ 
     pattern : { 
         params: someMoreRegex,
         message: "Another error"
    }
})

Is this a valid extension for a knockout observable (i.e. multiple pattern extensions)?

The regex for the second pattern is not being validated at all. In some cases it does get triggered but shows the first patterns error message. I have recently upgraded form 1.0.2 to 2.0.3 knockout validation and this has since broken but cannot seem to put a finger on why this is no longer working.

If I extend a knockout observable like so

var x = ko.observable().
extend({ 
     pattern : { 
         params: someRegex,
         message: "An error"
    }
})
.extend({ 
     pattern : { 
         params: someMoreRegex,
         message: "Another error"
    }
})

Is this a valid extension for a knockout observable (i.e. multiple pattern extensions)?

The regex for the second pattern is not being validated at all. In some cases it does get triggered but shows the first patterns error message. I have recently upgraded form 1.0.2 to 2.0.3 knockout validation and this has since broken but cannot seem to put a finger on why this is no longer working.

Share Improve this question edited Jun 27, 2016 at 13:56 Maciej Grzyb 5632 silver badges11 bronze badges asked Jun 27, 2016 at 8:37 SimSim 5901 gold badge10 silver badges22 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

From this (admitedly, quite old) Github issue, I concluded that this isn't supported by the validation library...

A quick fix could be to create anonymous custom rules that borrow the validator method from the pattern extension.

An example (which doesn't make sense, but shows how you can bine two patterns with their own errors):

this.name = ko.observable("").extend({
  validation: [{
      validator: ko.validation.rules['pattern'].validator,
      message: "Must be lowercase",
      params: /^[a-z]+$/
    }, {
      validator: ko.validation.rules['pattern'].validator,
      message: "Must be uppercase",
      params: /^[A-Z]+$/
    }
  ]
});

You could maybe clean this code up a bit by creating a factory method that returns the required objects, or create a custom rule that takes an array of regular expressions and an array of error messages.

发布评论

评论列表(0)

  1. 暂无评论