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

If I extend a knockout observable like sovar x = ko.observable().extend({ pattern : { params: someRege

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745405283a4626285.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信