开发者

Mongoose failing to validate array properties

I'm having some issues with validating an array property in Mongoose.

When I use the following definition, my shouldFail method never gets called, and the record always saves.

shouldFail = (v开发者_如何学Cal) ->
  console.log "Fail method called with value:"
  console.log val
  return false

definitions:
  english: [
    type: String
    validate: [ shouldFail, "testing" ]
    required: true
  ]

However if I set up validation as the following, the function gets called and the record is not saved.

Sense.path('definitions.english').validate (val) ->
  console.log "Validating English"
  console.log val
  return false

I'd prefer to use the former definition style if possible. I'm just wondering if I'm doing something wrong in my definition. Is that how you define validation for arrays?

Also I'm not sure if the way I'm setting english is affecting this. I'm just doing definitions.english = [ ] and trying to save.


I don't think you need the [] on english:, fiddling with the code on the coffeescript compiler it renders out way wrong if you include them. That is likely why your validation isn't working in that format. Try just:

definitions:
  english:
    type: String
    validate: [ shouldFail, "testing" ]
    required: true


I can see the question and chosen answer are quite old, but I think it may still be useful to elaborate a bit more.

It seems you can't validate a single element of an array. Instead run validation on entire array and loop through it's values if needed.

Assuming valid is a function to validate a single element:

definitions:
  english: 
    type      : [ String ]
    validate  :

      validator : (values) ->
        for value in values
          if not (valid value) then return false
        return true

      msg       : "At least one not valid"

  ]

By setting required flag I assume you wanted to make sure at least one element is in the array. To achive that, add another validate object like that:

definitions:
  english: 
    type      : [ String ]
    validate  : [  
      validator : (values) -> values.length # 0 is a falsy value
      msg       : "At least one required"                
    ,
      validator : (values) ->
        for value in values
          if not (valid value) then return false
        return true
      msg       : "At least one not valid"
    ]
  ]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜