Ruby On Rails 常用内建模型校验器

1、约定

现有模型 User,属性包括 :id,  :username,  :password,  :email,  :age,  :sex。

2、常用的模型校验器

Rails应用程序中的 ActiveRecord 提供了一套常用且简单的模型校验器,可以完成大多数情况下的校验工作

  • 非空校验:validates_presence_of
  • 唯一校验:validates_uniqueness_of
  • 数据长度校验:validates_length_of
  • 数值校验:validates_numericality_of
  • 数据格式校验:validates_format_of
  • 确认校验:validates_confirmation_of

3、非空校验:validates_presence_of

用户名不可为空,例:

class User < ActiveRecord::Base
    validates_presence_of :username, :message => "username can not null"
end



可选参数

:message 验证提示信息

4、唯一校验:validates_uniqueness_of

用户名不可重复,例:

class User < ActiveRecord::Base
  validates_uniqueness_of :username, :message => "username can not be same"
end



可选参数

:message 验证提示信息
:scope 验证基于多个参数的唯一属性值
:case_sensitive 大小写是否敏感
:allow_nil 是否允许nil值
:allow_blank 是否允许空值

5、数据长度校验:validates_length_of

用户名长度大于6,小于50,例:



class User < ActiveRecord::Base
  validates_length_of :username, :minimum => 6, :maximum => 50, :too_short => "username is too short", :too_long => "username is too long"
end

可选参数

:minimum 定义最小长度
:maximum 定义最大长度
:is 属性值的精确长度
:within 属性值长度的有效范围
:allow_nil 是否允许nil值
:too_short 长度小于最小值时的提示信息
:too_long 长度大于最大值时的提示信息
:wrong_length 属性值不匹配时的提示信息

6、数值校验:validates_numericality_of

用户年龄需为整数,并且不能大于70,小于16,例:



class User < ActiveRecord::Base
  validates_length_of :age, :only_integer => true, :greater_than => 70, :less_than => 16, :message => "age is not in scope"
end

可选参数

:message 验证提示信息
:only_integer 是否必须为整数
:greater_than 属性值必须大于或等于该项指定值
:greater_than_or_equal_to 属性值必须大于或等于该项指定值
:equal_to 属性值必须等于该项指定值
:less_than 属性值必须小于该项指定值
:less_than_or_equal_to 属性值必须小于或等于该项指定值
:odd 属性值必须为奇数
:even 属性值必须为偶数

7、数据格式校验:validates_format_of

用户邮箱格式验证(更多常用正则表达式),例:



class User < ActiveRecord::Base
  validates_format_of :email, :with => /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/, :message => "email parten is illegal"
end

可选参数

:message 验证提示信息
:with 需要匹配的正则表达式

8、确认校验:validates_confirmation_of

注册用户时,两次密码填写一致,例:



class User < ActiveRecord::Base
  validates_confirmation_of :password, :message => "password is not same"
end

该验证方法需要配合表单实现,Rails HTML内容为:

<%= f.text_field :password %>
<%= f.text_field :password_confirmation %>

可选参数

:message 验证提示信息

转载于:https://my.oschina.net/H7QMCSeOLOxu/blog/170546

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值