简体   繁体   English

在表单中验证Rails中的多个字段

[英]Validate multiple fields in rails in the form

I have this form in my app, I want to validate couple of fields of the form. 我的应用程序中有此表单,我想验证表单的几个字段。 Ie I want to make them as required field during a form submission. 即我想在表单提交期间将它们作为必填字段。

Is there any way so that I don't have to use any gem or any good gem that is straightforward for this particular task? 有什么方法可以使我不必为此任务使用任何简单的好宝石?

<div class="col-md-4">
  <div class="form-group">
    <div class="field">
      <%= f.label :name %><br />
      <%= f.text_field :name, :class=>"form-control", :placeholder=>"Enter Your Name" %>
    </div>
    <div class="field">
      <%= f.label :email %><br />
      <%= f.text_field :email, :class=>"form-control", :placeholder=>"Enter Your Password"%>
      </div>
    <div class="field">
      <%= f.label :phone %><br />
      <%= f.text_field :phone, :class=>"form-control", :placeholder=>"Enter Your Phone Number"%>
      </div>
   </div> 
</div>

<div class = "col-md-8">
   <div class="form-group">
     <div class="field">
      <%= f.label :description %><br />
      <%= f.text_area :description,  :class=>"form-control", :size=>"20x5", :placeholder=>"Enter Your Message"%>
     </div>
   </div>
</div>

<div class="actions">
  <%= f.submit "Submit", :class=> "button1"%>
</div> 

Thanks in advance 提前致谢

We can have various plugins for client side validations. 我们可以提供用于客户端验证的各种插件。 You can chose jquery_validate for this purpose. 您可以为此选择jquery_validate。 Refer : http://jqueryvalidation.org/ 请参阅: http : //jqueryvalidation.org/

But client side validation is not always reliable. 但是客户端验证并不总是可靠的。 If you disable browser javascript the validation won't work anymore. 如果您禁用浏览器JavaScript,则验证将不再起作用。

But from user experience point of view, Consider implementing client side validations. 但是从用户体验的角度来看,请考虑实施客户端验证。 But application security point of view you should consider having server side validations as well. 但是从应用程序安全性的角度来看,您还应该考虑进行服务器端验证。

  validates :name, 
    presence: { message: "Organization name is mandatory." }

  validates :address, presence: {message: 'Address is mandatory.'}

  validates :description, presence: { message: 'Description is mandatory'}
  validates_length_of :name, 
    maximum: 50, too_long: "Maximum 50 characters allowed."

  validates_length_of :address, :description, 
    maximum: 300, too_long: "Maximum 300 characters allowed."

Hope it helps you :) 希望它能对您有所帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM