当前位置: 动力学知识库 > 问答 > 编程问答 >

Javascript Validation Framework for Backbone.js

问题描述:

Backbone.js comes with model validation events, and I'm looking to integrate it with a lite validation framework.

I just started looking at http://happyjs.com/

any other recommendations?

网友答案:

jQuery Validate is my favorite its well documented and used by many

网友答案:

Try the Backbone.Validations plugin

网友答案:

There are some validations plugins for backbone but I don't like it, I ended up with this:

...
validate: (attrs) ->
  helper = @validationHelper attrs
  helper.check 'name', (v) -> "can't be blank" if _(v).isBlank()
  helper.check 'version', (v) -> "can't be blank" if _(v).isBlank()
  helper.check 'organization', (v) -> "can't be blank" if _(v).isBlank()
  helper.errors()
...

And here's the helper:

  _(Backbone.Model.prototype).extend
    validationHelper: (attrs) ->
      helper = 
        _errors: {}
        check: (name, validator) ->
          return unless attrs and (name of attrs)
          msg = validator attrs[name]
          (@_errors[name] ?= []).push msg if msg
          @
        errors: -> if _(@_errors).any() then @_errors else null
      return helper
分享给朋友:
您可能感兴趣的文章:
随机阅读: