在使用带有Angularjs客户端表单验证的Rails表单时,使用字段名

时间:2021-06-10 18:57:41

I'm trying to use Angularjs for client-side form validation in my Rails Project. I'm using the build-in ng-show directive to display errors for form fields. The code is very simple:

我正在尝试在Rails项目中使用Angularjs进行客户端表单验证。我使用内置的ng-show指令来显示表单字段的错误。代码非常简单:

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), 
                              html: { novalidate: true, name: 'signUpForm'}) do |f| %>
  ...

  <%= f.email_field :email, :'ng-model'=>'user.email', name: 'uEmail', 
                              autofocus: true, required: true %>
  ...

  <div ng-show="signUpForm.uEmail.$dirty && signUpForm.uEmail.$invalid">
    <span ng-show="signUpForm.uEmail.$error.required">
      <small class="error">Tell us your email.</small>
    </span>
    <span ng-show="signUpForm.uEmail.$error.email">
      <small class="error">This is not a valid email.</small>
    </span>
  </div>
<% end %>

This gives me a nice client-side validation, but the problem is, since Rails by default gives a form field name like model[attr] in my case user[email]

这给了我一个很好的客户端验证,但是问题是,由于Rails默认提供了一个表单字段名,比如model[attr]在我的案例用户[email]中

However, here I give my email field a name uEmail and params in the post request after submit the form will be uEmail: 'xxx@xx.xx' which rails is unable to understand ( by default Rails is expecting something like user: { email: 'xxx@xx.xx' ... } )

然而,我在这里给我的电子邮件字段一个名称uEmail和params在提交后的邮件请求将是uEmail: 'xxx@xx。xx'是rails无法理解的(默认情况下,rails期望用户:{email: 'xxx@xx。xx”……})

I tried to remove name: 'uEmail' and fall back to Rails default user[email] and use something like this in ng-show directive

我试图删除名称:“uEmail”,回到Rails默认用户[email],并在ng-show指令中使用类似的东西

<span ng-show="signUpForm.user[email].$error.required">

But This won't work, anyone has any idea how to get around with this?

但这行不通,谁知道怎么解决这个问题?

btw: rails -v 4.0 Angularjs version: 1.0.7

rails - v4.0 Angularjs版本:1.0.7

1 个解决方案

#1


3  

I don't know if you since found a solution to this issue, I was facing the same problem, I found an issue had been opened on GitHub :

我不知道你是否找到了解决这个问题的办法,我当时也遇到了同样的问题,我发现GitHub上有个问题被打开了:

https://github.com/angular/angular.js/issues/1201

https://github.com/angular/angular.js/issues/1201

The solution is pretty simple, in your case you simply do :

解决办法很简单,你只需:

<span ng-show="signUpForm['user[email]'].$error.required">

#1


3  

I don't know if you since found a solution to this issue, I was facing the same problem, I found an issue had been opened on GitHub :

我不知道你是否找到了解决这个问题的办法,我当时也遇到了同样的问题,我发现GitHub上有个问题被打开了:

https://github.com/angular/angular.js/issues/1201

https://github.com/angular/angular.js/issues/1201

The solution is pretty simple, in your case you simply do :

解决办法很简单,你只需:

<span ng-show="signUpForm['user[email]'].$error.required">