ember.js - EmberJS 中的表单验证

标签 ember.js

我只是想知道在 EmberJS 中验证表单的一般模式是什么?对于我的 App.IndexView 我有一个表单,当您单击提交按钮时,目标设置为 View ,因此我可以进行一些验证。在我需要对有错误的字段做一些事情之前,这非常有效。我只想在有错误的字段中添加一个类,但不确定该怎么做。 IndexView 应该验证表单,还是应该为每个字段创建一个 View ,以在模糊时验证其自身?以下是我的 IndexView 中的内容。

App.IndexView = Ember.View.extend


  create: (model) ->

    valid = @_validate model

    if valid is true
      @get('controller').send 'createUser'
    else
      # HANDLE THE FIELDS WITH ERRORS

  _validate: (model) ->

    invalid = []
    validations = {
      firstName: @_validateString model.get 'firstName'
      lastName: @_validateString model.get 'lastName'
      email: @_validateEmail model.get 'email'
      password: @_validatePassword model.get 'password'
      accountType: @_validateString model.get 'accountType'
    }

    # This will get all of the values then runs uniq to see if the
    # form is valid
    validForm = _.chain(validations).values().uniq().value()

    if validForm.length is 1 and validForm[0]
      true
    else
      # other wise build up an array of the fields with issues
      for field, val of validations
        if val is false
          invalid.push field

      invalid

  _validateString: (str) ->
    return false unless str
    if str isnt '' then true else false

  _validateEmail: (str) ->
    pattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    pattern.test str

  _validatePassword: (str) ->
    return false unless str
    if str.length >= 6 then true else false

和模板
<div class="row">
  <div class="span12">
    <div class="signup">
      <form class="form-horizontal offset3">
        <div class="control-group">
          <label class="control-label" for="first_name">First Name</label>
          <div class="controls">
            {{ view Ember.TextField placeholder="First Name" required="true" valueBinding='firstName' name='first_name' viewName='firstNameField'}}
          </div>
        </div>
        <div class="control-group">
          <label class="control-label" for="last_name">Last Name</label>
          <div class="controls">
            {{ view Ember.TextField placeholder="Last Name" required="true" valueBinding='lastName' name='last_name' viewName='lastNameField'}}
          </div>
        </div>
        <div class="control-group">
          <label class="control-label" for="email">Email</label>
          <div class="controls">
            {{ view Ember.TextField placeholder="Email" required="true" type="email" valueBinding='email' name='email' viewName='emailField'}}
          </div>
        </div>
        <div class="control-group">
          <label class="control-label" for="password">Password</label>
          <div class="controls">
            {{ view Ember.TextField placeholder="Password" required="true" type="password" valueBinding='password' name='password' viewName='passwordField'}}
          </div>
        </div>
        <div class="control-group">
          <label class="control-label" for="">Account Type</label>
          <div class="controls">
            {{#view Ember.RadioButtonGroup name="accountType" required="true" valueBinding="accountType"}}
              <label class="radio">
                {{view RadioButton checked='false' value="landlord"}}
                Landlord
              </label>
              <label class="radio">
                {{view RadioButton checked='false' required="true" value="tenant"}}
                Tenant
              </label>
            {{/view}}
          </div>

        </div>
        <div class="control-group">

          <div class="controls">
            <input class="btn btn-primary" {{action create model target='view' }} type="submit" value="Sign Up">
          </div>

        </div>
      </form>

    </div>

  </div>

</div>

最佳答案

I'm just wondering what the general pattern for validating forms in EmberJS?



似乎有几种模式在使用。这在很大程度上取决于正在验证的内容,一般策略是使业务逻辑尽可能远离 View 层。以下是一些可能有用的链接:
  • validations-in-emberjs-application.html建议在 Controller 级别执行验证, View 用于在焦点更改时触发验证。此截屏视频演示了如何使用此模式来验证一些简单的表单字段。
  • Asynchronous-Form-Field-Validation-With-Ember提供了一些可重用的组件,可用于在 View 层执行简单的验证。
  • ember-validations是一个库,可用于将事件记录样式验证功能添加到任何 ember 对象

  • For my App.IndexView I have a form and when you click the submit button the target set to the view so I can do some validation. This works great up to the point where I need to do something with the fields that have errors. I would like to just add a class to the field of erro but not really sure how to do it.



    因为您希望一次验证多个字段,所以将这个验证逻辑移到 Controller 中可能更有意义。无论哪种方式,通常您会将给定字段的类属性绑定(bind)到属性,如下所示:
    <div class="controls" {{bindAttr class=firstNameError:error:success}}>
      {{ view Ember.TextField placeholder="First Name" required="true" valueBinding='firstName' name='first_name' viewName='firstNameField'}}
    </div>
    

    因此,添加一个 firstNameError根据验证结果返回真/假的属性。鉴于您的实现,在 _validate 时设置此属性可能是有意义的。已运行,但它也可以是实时执行验证的计算属性。

    Should the IndexView validate the form or should I create a view for each field that validates its self on blur?



    这实际上取决于您希望用户体验是什么样的。 FWIW 我的投票是模糊。

    关于ember.js - EmberJS 中的表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14609303/

    相关文章:

    javascript - 如何使用 Ember ArrayController 获取对象集合?

    ember.js - 使用 ember-data 处理 GET/models 返回的部分或摘要对象列表

    javascript - EMBER—断言失败 : Error while loading route: TypeError: Object [object Object] has no method 'addArrayObserver'

    ember.js - 使用 Ember.js 处理 Controller 间关系的正确方法

    javascript - 使用 handlebars 或 markdown 输出模型属性

    javascript - Ember.js 路由器和 initialState 中的嵌套路由

    javascript - Ember.js:如何在模态弹出窗口中的模板上显示模型的当前内容

    ruby - 单页应用程序中的elasticsearch

    javascript - 在 emberjs 中动态创建模型时检测事件

    javascript - 路由器 Action 和 Controller Action 有什么区别?