zoukankan      html  css  js  c++  java
  • 手把手教你学习ROR-5.Validation

    Rails应用一般有三层校验

    1 在Client端,可以使用JQuery-Validation 框架

    2 在Controller端,配置Model时的validate,会在Controller调用save,update之前进行校验

    • create
    • create!
    • save
    • save!
    • update
    • update!

    3 Database,在schema中设置

    A 校验方法

    1 校验存在性

    validates :email,:password, presence: true

    2 校验字段长度

    validates :nickname, length: { minimum: 2,maximum:20}

    3 验证唯一性

    validates :email, uniqueness: true

    4 校验格式

    validates :email, format: { with:/@/}

    5 校验是否为数字

    validates :user_id, numericality: { only_integer: true }

    6 验证字段是否不存在,string是否为空或者为“”,可以用present校验这个字段

    validates :name, :login, :email, absence: true

    7 验证某个字段是否在集合内

     validates :size, inclusion: { in: %w(small medium large), message: "%{value} is not a valid size"}

    8 验证某个字段不在集合内

    validates :domain, exclusion: { in: %w(www us ca jp), message: "Subdomain %{value} is reserved."}

    9 用自己的Valiator类来进行校验

    validates_with GoodnessValidator, fields: [:first_name, :last_name]

    10 需要确认confirmation进行校验

     validates :email, confirmation: true

    B 其他字段

    1allow_nil

    validates :sex, inclusion: { in: %w(boy girl), message: "%{value} is not a sex type" },allow_nil: true

    2 allow_blank

    validates :sex, inclusion: { in: %w(boy girl), message: "%{value} is not a sex type" },allow_blank: true

    3 message

    validates :sex, inclusion: { in: %w(boy girl), message: "%{value} is not a sex type" },allow_nil: true

    4 on

    validates :email, uniqueness: true, on: :create

    5 strict(可以自己定制Exception,当validate不通过时,raise Exception)

    validates :token, presence: true, uniqueness: true, strict: TokenGenerationException

    6 if

    validates :surname, presence: true, if: "name.nil?"

    7 unless

    validates :surname, presence: true, unless: "name.nil?"

    C Validation in the view

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

      

  • 相关阅读:
    IOS-JSON数据解析
    IOS-APP发布资料收集
    IOS-webService
    ASP.NET MVC学习之路:模板页
    io流
    线程
    事件监听
    java基础面试题
    递归调用
    三目运算: x?y:z
  • 原文地址:https://www.cnblogs.com/SoulSpirit/p/3419863.html
Copyright © 2011-2022 走看看