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

一、约定

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

二、经常使用的模型校验器

Rails应用程序中的 ActiveRecord 提供了一套经常使用且简单的模型校验器,能够完成大多数状况下的校验工做 正则表达式

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

三、非空校验:validates_presence_of

用户名不可为空,例: ruby

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



可选参数 less

:message 验证提示信息

四、惟一校验:validates_uniqueness_of

用户名不可重复,例: spa

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



可选参数 code

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

五、数据长度校验:validates_length_of

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



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

可选参数 htm

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

六、数值校验:validates_numericality_of

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



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

可选参数 it

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

七、数据格式校验: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 须要匹配的正则表达式

八、确认校验: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 验证提示信息
相关文章
相关标签/搜索