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

      

  • 相关阅读:
    css样式的调用方法
    分页的实现 (占个位)
    获取当前脚本的进程PID号
    Mail插件 (占个位 后面补充)
    ovs-vswitchd的启动分析
    OPCServer:使用Matrikon OPC Server Simulation
    OPCServer:使用KEPServer
    Java OPC 代码
    OPC 协议认识
    OPC 技术学习总结
  • 原文地址:https://www.cnblogs.com/SoulSpirit/p/3419863.html
Copyright © 2011-2022 走看看