EmberJS中的表单验证 [英] Form Validations in EmberJS

查看:122
本文介绍了EmberJS中的表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道在EmberJS中验证表单的一般模式是什么?对于我的App.IndexView我有一个表单,当你点击提交按钮的目标设置为视图,所以我可以做一些验证。这样做很好,直到我需要对有错误的字段做一些事情。我想只是添加一个类到有错误的字段,但不确定如何做到这一点。如果IndexView验证表单,还是应该为每个字段创建一个视图来验证自己的模糊?以下是我在IndexView中的内容。

  App.IndexView = Ember.View.extend 


create:(model) - >

valid = @_validate model

如果有效为真
@get('controller')。发送'createUser'
else
#处理带有错误的字段

_validate:(model) - >

无效= []
验证= {
firstName:@_validateString model.get'firstName'
lastName:@_validateString model.get'lastName'
电子邮件:@_validateEmail model.get'email'
密码:@_validatePassword model.get'password'
accountType:@_validateString model.get'accountType'
}

#这将获得所有的值,然后运行uniq来查看
#形式是否有效
validForm = _.chain(validations).values()。uniq()。value()

如果validForm.length为1,validForm [0]
true
else
#其他明智的建立一个字段数组,问题
为字段,验证值
如果val为false
invalid.push字段

无效

_validateString:(str) - >
返回false除非str
if str isnt''then true else false

_validateEmail:(str) - >
pattern = / ^(([^;;;;;;(((((((((((((((((((((( )[\] \\;:。\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) - >
返回false除非str
如果str.length> = 6则为true否则false

和模板

 < div class =row> 
< div class =span12>
< div class =signup>
< form class =form-horizo​​ntal offset3>
< div class =control-group>
< label class =control-labelfor =first_name>名字< / label>
< div class =controls>
{{view Ember.TextField placeholder =First Namerequired =truevalueBinding ='firstName'name ='first_name'viewName ='firstNameField'}}
< / div>
< / div>
< div class =control-group>
< label class =control-labelfor =last_name>姓氏< / label>
< div class =controls>
{{view Ember.TextField placeholder =Last Namerequired =truevalueBinding ='lastName'name ='last_name'viewName ='lastNameField'}}
< / div>
< / div>
< div class =control-group>
< label class =control-labelfor =email> Email< / label>
< div class =controls>
{{view Ember.TextField placeholder =Emailrequired =truetype =emailvalueBinding ='email'name ='email'viewName ='emailField'}}
< / div> ;
< / div>
< div class =control-group>
< label class =control-labelfor =password> Password< / label>
< div class =controls>
{{view Ember.TextField placeholder =Passwordrequired =truetype =passwordvalueBinding ='password'name ='password'viewName ='passwordField'}}
< / div> ;
< / div>
< div class =control-group>
< label class =control-labelfor =>帐户类型< / label>
< div class =controls>
{{#view} Ember.RadioButtonGroup name =accountTyperequired =truevalueBinding =accountType}}
< label class =radio>
{{查看RadioButton checked ='false'value =房东}}
楼主
< / label>
< label class =radio>
{{view RadioButton checked ='false'required =truevalue =tenant}}
租户
< / label>
{{/ view}}
< / div>

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

< div class =controls>
< input class =btn btn-primary{{action create model target ='view'}} type =submitvalue =注册>
< / div>

< / div>
< / form>

< / div>

< / div>

< / div>


解决方案


我只是想知道EmberJS中验证表单的一般模式是什么?


似乎有几种模式正在使用中。它取决于正在验证的内容,总体策略是将业务逻辑尽可能远离视图层。以下是一些可能证明有用的链接:






对于我的App.IndexView我有一个表单,当你点击提交按钮的目标设置为视图,所以我可以做一些验证。这样做很好,直到我需要对有错误的字段做一些事情。我想添加一个课程到erro的领域,但不知道该怎么做。


为了一次验证一些字段,将该验证逻辑转移到控制器中可能更有意义。无论哪种方式,通常会将给定字段的类属性绑定到属性,如下所示:

 < div class =控件{{bindAttr class = firstNameError:error:success}}> 
{{view Ember.TextField placeholder =First Namerequired =truevalueBinding ='firstName'name ='first_name'viewName ='firstNameField'}}
< / div>

所以这样就可以添加一个 firstNameError 属性根据验证结果返回true / false。考虑到您的实现,在 _validate 运行时设置此属性可能是有意义的,但它也可以是实时执行验证的计算属性。


如果IndexView验证表单,还是应该为每个字段创建一个验证其自我模糊的视图?


这真的取决于你想要的用户体验。 FWIW我的投票是模糊的。


I'm just wondering what the general pattern for validating forms in EmberJS? 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 fields with errors but not really sure how to do it. Should the IndexView validate the form or should I create a view for each field that validates its self on blur? Below is what I have in my 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

and the template

<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?

There seem to be several patterns in use. It depends quite a bit on what is being validated, with the general strategy being to keep business logic far from the view layer as possible. Here are some links that may prove useful:

  • validations-in-emberjs-application.html recommends performing validation at the controller level, with views are used to trigger validation when focus changes. This screencast demonstrates how this pattern can be used to validate a few simple form-fields.

  • Asynchronous-Form-Field-Validation-With-Ember provides a few reusable components that can be used to perform simple validations at the view layer.

  • ember-validations is a library that can be used to add active-record style validation capabilities to any ember-object

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.

since you're looking to validate a number of fields at once it might make more sense to move this validation logic into the controller. Either way, typically you would bind class attributes for a given field to a property as follows:

<div class="controls" {{bindAttr class=firstNameError:error:success}}>
  {{ view Ember.TextField placeholder="First Name" required="true" valueBinding='firstName' name='first_name' viewName='firstNameField'}}
</div>

So with this in place add a firstNameError property that returns true/false depending on results of your validation. Given your implementation it would probably make sense to set this property when _validate is run, but it could also be a computed property that performs validation in real-time.

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

That really depends on what you want the user experience to be like. FWIW my vote is to go with on-blur.

这篇关于EmberJS中的表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆