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
用户名不可为空,例:
|
|
可选参数
:message | 验证提示信息 |
4、唯一校验:validates_uniqueness_of
用户名不可重复,例:
|
|
可选参数
: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 | 验证提示信息 |