简体   繁体   English

在 rails 中对 html 进行验证

[英]Puts out validations to html in rails

I am trying to achieve how to put the validations error from backend to front end in rails我正在尝试实现如何将验证错误从后端到前端放入 rails

Here is my user.rb :这是我的user.rb

class User < ActiveRecord::Base
  has_secure_password

  EMAIL_REGEX = /\A([^@\s]+)@((?:[a-z0-9]+\.)+[a-z]+)\z/i
  validates :name, presence: true
  validates :email, presence: true, uniqueness: {case_Sensitive:false }, format: { with: EMAIL_REGEX}
  validates :password, presence: true, length: { minimum: 5 }

  before_save :email_lowercase

  # makes email lowercase before user submits

  def email_lowercase
    email.downcase!
  end

end

and here is my user_controller.rb :这是我的user_controller.rb

  def create
    user = User.create(user_params)
    if user.valid?
      user.save
      redirect_to 'index'
    else
      user.errors.messages
      redirect_to '/users/new'
    end
  end

and this is my html form:这是我的 html 表格:

<form action="/users" method="post">
    <%= hidden_field_tag :authenticity_token, form_authenticity_token %>

    <input type="text" name="user[name]" placeholder="Name"><br>
    <input type="text" name="user[email]" placeholder="Email"><br>
    <input type="password" name="user[password]" placeholder="Password"><br>
    <input type="password" name="user[confirm_pw]" placeholder="Confirm PW">
    <input type="submit" value="Join">

</form>

How can I puts out validations to html in rails?如何在 rails 中对 html 进行验证?

Have a look at section about adding validations in the Getting Started with Rails guide.查看Rails 入门指南中有关添加验证的部分。 There you'll find a good example.在那里你会找到一个很好的例子。 For your form, you could add the following:对于您的表单,您可以添加以下内容:

  <% if @user.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= pluralize(@user.errors.count, "error") %> prohibited
        this user from being saved:
      </h2>
      <ul>
        <% @user.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

For this to work, you'll also have to make some changes to your controller, so that you'll have a @user instance variable available.为此,您还必须对 controller 进行一些更改,以便您可以使用@user实例变量。

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

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