validates

本文详细介绍了Rails框架中的各种数据验证方法,包括自定义验证、常见内置验证如presence、uniqueness等,以及如何针对不同场景应用合适的验证选项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以自定义validate(), 这个方法在每次保存数据时都会被调用.
如:
def validate
if name.blank? && email.blank?
    errors.add_to_base("You mustspecify a name or an email address")
end
end
同时也可以自定义 validate_on_create(),validate_on_update()方法.
valid?()方法可以随时调用,用来测试数据是否能通过校验
返回的错误信息可用 error_messages_for(model)方法显示.
如:<%= error_messages_for 'article' %>

校验大全:
validates_acceptance_of
指定checkbox应该选中. (如:(*)我同意条款)
用法:validates_acceptance_of attr... [ options...]
参数:message text    默认:“mustbe accepted.”
     :on :save,:create, or :update
实例:
class Order < ActiveRecord::Base
    validates_acceptance_of:terms,
                :message=> "Please accept the terms to proceed"
end
validates_associated
查验指定的object.
用法:validates_associated name... [ options...]
参数:message text 默认: is “is invalid.”
     :on :save,:create, or :update
实例:
class Order < ActiveRecord::Base
    has_many :line_items
    belongs_to :user
    validates_associated:line_items,
              :message=> "are messed up"
    validates_associated:user
end
validates_confirmation_of
数据重校
用法:validates_confirmation_of attr... [options... ]
参数:message text 默认 “doesn’t matchconfirmation.”
     :on :save,:create, or :update
实例:
对密码表:
<%= password_field "user", "password"%><br />
<%= password_field "user","password_confirmation" %><br />
#第二表名为xxxx_confirmation
class User < ActiveRecord::Base
    validates_confirmation_of:password
end
validates_each
使用block检验一个或一个以上参数.
用法:validates_each attr... [ options... ] {|model, attr, value| ... }
参数:allow_nilboolean 设为true时跳过nil对象.
     :on :save,:create, or :update
实例:
class User < ActiveRecord::Base
    validates_each :name, :email do|model, attr, value|
     ifvalue =~ /groucho|harpo|chico/i
      model.errors.add(attr,"Youcan't be serious, #{value}")
     end
    end
end
validates_exclusion_of
确定被检对象不包括指定数据
用法:validates_exclusion_of attr..., :in =>enum [ options... ]
#enum指一切可用include?()判断的范围.
参数:allow_nil 设为true将直接跳过nil对象.
     :in (or:within) enumerable
     :message text默认为: “is not included in the list.”
     :on :save,:create, or :update
实例:
class User < ActiveRecord::Base
    validates_exclusion_of:genre,
              :in=> %w{ polka twostep foxtrot },
              :message=>"no wild music allowed"
    validates_exclusion_of:age,
               :in=> 13..19,
               :message=>"cannot be a teenager"
end
validates_inclusion_of
确认对象包括在指定范围
用法:validates_inclusion_of attr..., :in =>enum [ options... ]
参数:allow_nil 设为true直接跳过nil对象
     :in (or:within) enumerable An enumerable object.
     :message text默认:“is not included in the list.”
     :on :save,:create, or :update
实例:
class User < ActiveRecord::Base
    validates_inclusion_of:gender,
              :in=> %w{ male female },
              :message=>"should be 'male' or 'female'"
    validates_inclusion_of:age,
              :in=> 0..130,
              :message=>"should be between 0 and 130"
end
validates_format_of
用正则检验对象
用法:validates_format_of attr..., :with =>regexp [ options... ]
参数:message text 默认为: “is invalid.”
     :on :save,:create, or :update
     :with正则表达式
实例:
class User < ActiveRecord::Base
    validates_format_of :length,:with => /^\d+(in|cm)/
end
validates_length_of
检查对象长度
用法:validates_length_of attr..., [ options...]
参数:in (or :within) range
     :isinteger
     :minimuminteger
     :maximuminteger
     :message text默认文字会根据参数变动,可使用%d取代确定的最大,最小或指定数据.
     :on :save,:create, or :update
     :too_longtext 当使用了 :maximum后的 :message
     :too_shorttext ( :minimum )
     :wrong_length( :is)
实例:
class User < ActiveRecord::Base
    validates_length_of :name,:maximum => 50
    validates_length_of :password,:in => 6..20
    validates_length_of :address,:minimum => 10,
                  :message=>"seems too short"
end
validates_numericality_of
检验对象是否为数值
用法:validates_numericality_of attr... [options... ]
参数:message text 默认 “is not a number.”
     :on :save,:create, or :update
     :only_integer
实例:
class User < ActiveRecord::Base
    validates_numericality_of:height_in_meters
    validates_numericality_of :age,:only_integer => true
end
validates_presence_of
检验对象是否为空
用法:validates_presence_of attr... [ options...]
参数:message text 默认:“can’t be empty.”
     :on :save,:create, or :update
实例:
class User < ActiveRecord::Base
    validates_presence_of :name,:address
end
validates_uniqueness_of
检验对象是否不重复
用法:validates_uniqueness_of attr... [ options...]
参数:message text 默认: “has already beentaken.”
     :on :save,:create, or :update
     :scope attr指定范围
实例:
class User < ActiveRecord::Base
    validates_uniqueness_of:name
end
class User < ActiveRecord::Base
    validates_uniqueness_of :name,:scope =>"group_id"
end
#指定在同一group_id的条件下不重复.

常用正则:

E-Mail地址格式:
validates_format_of      :email,
                         :with        => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
                         :message     => 'email must be valid'

网址格式:
validates_uri_existence_of :url, :with =>
         /(^$)|(^(http|https)://[a-z0-9] ([-.]{1}[a-z0-9])*.[a-z]{2,5}(([0-9]{1,5})?/.*)?$)/ix
### 回答1: validates resource references的意思是验证资源引用。在编程中,我们经常需要引用其他资源,如数据库表、文件等。使用validates resource references可以确保我们引用的资源是有效的,避免出现错误。这个功能在编写高质量的代码时非常重要。 ### 回答2: 在编程领域中,validates resource references(验证资源引用)指的是检查和确认程序中所引用的资源是否有效、存在且正确。资源引用可以包括文件、数据库记录、网络连接、API 接口等。 验证资源引用的主要目的是确保程序能够正确地访问和使用所需的资源,以避免出现潜在的错误和异常情况。这一过程可以在程序运行前、运行中或运行后进行。通过验证资源引用,我们可以确保所调用的资源不存在错误或不可用的情况,从而提高程序的稳定性和可靠性。 验证资源引用通常涉及以下几个方面: 1. 存在性检查:验证程序所引用的资源是否存在,以防止程序在不可用资源上操作,避免了可能的崩溃和异常情况。 2. 格式检查:验证资源引用的格式是否正确,例如检查文件路径是否有效、数据库记录是否合法等。这可以保证资源的正确访问和使用。 3. 访问权限检查:验证程序是否具有访问所需资源的权限,例如文件读写权限、数据库查询权限等。这可以保护程序的安全性和数据的完整性。 4. 连接测试:验证程序与所引用的网络资源或服务的连接是否正常,以确保程序能够正确地使用这些资源。 通过对资源引用进行验证,我们可以尽早地发现和解决潜在的问题,提高程序的健壮性和可维护性。此外,验证资源引用还可以增加程序的可测试性,方便进行单元测试和集成测试,从而提高开发效率。 ### 回答3: 验证资源引用是一种用于确保所引用的资源存在且有效的操作。当我们在开发应用程序或系统时,经常需要引用和使用其他资源,如数据库、文件、网络连接等。在使用这些资源之前,我们需要确保它们是有效的,否则可能会导致应用程序崩溃或功能异常。 验证资源引用可以通过一些方式进行。首先,可以检查资源的存在性。例如,在引用数据库时,我们可以检查数据库连接是否成功建立,或者在引用文件时,我们可以检查文件是否存在。如果资源不存在,我们需要采取相应的措施,如重新尝试建立连接或报告错误。 其次,验证资源引用还可以通过验证资源的正确性。例如,在引用数据库时,我们可以检查数据库表是否存在,或者在引用文件时,我们可以检查文件的格式是否正确。如果资源的内容不符合预期,我们可以采取相应的处理方法,如返回错误信息或进行数据转换。 验证资源引用对于确保应用程序的正常运行和准确性非常重要。它可以帮助我们在使用资源之前进行必要的检查和校验,避免潜在的问题和错误。同时,它还可以提供更好的用户体验和操作可靠性,让用户使用应用程序时更加顺畅和满意。因此,有效验证资源引用是开发高质量应用程序的重要一环。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值