`

validation

阅读更多

http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html


class Comment
  include ActiveModel::Validations

  validate :must_be_friends

  def must_be_friends
    errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
  end
end
Or with a block which is passed with the current record to be validated:

class Comment
  include ActiveModel::Validations

  validate do |comment|
    comment.must_be_friends
  end

  def must_be_friends
    errors.add(:base, ("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
  end
end

Examples of using the default rails validators:

validates :terms, :acceptance => true
validates :password, :confirmation => true
validates :username, :exclusion => { :in => %w(admin superuser) }
validates :email, :format => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create }
validates :age, :inclusion => { :in => 0..9 }
validates :first_name, :length => { :maximum => 30 }
validates :age, :numericality => true
validates :username, :presence => true
validates :username, :uniqueness => true

The power of the validates method comes when using custom validators and default validators in one call for a given attribute e.g.

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    record.errors[attribute] << (options[:message] || "is not an email") unless
      value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
  end
end

class Person
  include ActiveModel::Validations
  attr_accessor :name, :email

  validates :name, :presence => true, :uniqueness => true, :length => { :maximum => 100 }
  validates :email, :presence => true, :email => true
end
Validator classes may also exist within the class being validated allowing custom modules of validators to be included as needed e.g.

class Film
  include ActiveModel::Validations

  class TitleValidator < ActiveModel::EachValidator
    def validate_each(record, attribute, value)
      record.errors[attribute] << "must start with 'the'" unless value =~ /\Athe/i
    end
  end

  validates :name, :title => true
end
The validators hash can also handle regular expressions, ranges and arrays:

validates :email, :format => /@/
validates :gender, :inclusion => %w(male female)
validates :password, :length => 6..20
Finally, the options :if, :unless, :on, :allow_blank and :allow_nil can be given to one specific validator:

validates :password, :presence => { :if => :password_required? }, :confirmation => true
Or to all at the same time:

validates :password, :presence => true, :confirmation => true, :if => :password_required?



Validates each attribute against a block.

class Person
  include ActiveModel::Validations

  attr_accessor :first_name, :last_name

  validates_each :first_name, :last_name do |record, attr, value|
    record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
  end
end
Options:

:on - Specifies when this validation is active (default is :save, other options :create, :update).

:allow_nil - Skip validation if attribute is nil.

:allow_blank - Skip validation if attribute is blank.

:if - Specifies a method, proc or string to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to a true or false value.

:unless - Specifies a method, proc or string to call to determine if the validation should not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The method, proc or string should return or evaluate to a true or false value.



u = User.new
u.valid?
u.invalid?
u.valid?(:email)
u.errors
u.errors.on("email")
u.errors.full_messages


u1 = User.new
u1.errors => #<OrderedHash {}>
u1.save => false
u1.errors
=> #<OrderedHash {:password_confirmation=>["is too short (minimum is 4 characters)"], :password=>["is too short (minimum is 4 characters)"], :email=>["is too short (minimum is 6 characters)", "should look like an email address."]}>
u1.errors.add(:email, "is too short")
u1.errors.methods.grep /add/

u1=User.new
u1.errors => #<OrderedHash {}>
u1.valid? => false
u1.errors
=> #<OrderedHash {:password_confirmation=>["is too short (minimum is 4 characters)"], :password=>["is too short (minimum is 4 characters)"], :email=>["is too short (minimum is 6 characters)", "should look like an email address."]}>
u1.errors.delete(:email)
u1.errors
=> #<OrderedHash {:password_confirmation=>["is too short (minimum is 4 characters)"], :password=>["is too short (minimum is 4 characters)"]}>

分享到:
评论

相关推荐

    validation-api-1.1.0.Final-API文档-中文版.zip

    赠送jar包:validation-api-1.1.0.Final.jar; 赠送原API文档:validation-api-1.1.0.Final-javadoc.jar; 赠送源代码:validation-api-1.1.0.Final-sources.jar; 包含翻译后的API文档:validation-api-1.1.0....

    jakarta.validation-api-2.0.2-API文档-中文版.zip

    赠送jar包:jakarta.validation-api-2.0.2.jar; 赠送原API文档:jakarta.validation-api-2.0.2-javadoc.jar; 赠送源代码:jakarta.validation-api-2.0.2-sources.jar; 赠送Maven依赖信息文件:jakarta.validation...

    validation-api-2.0.1.Final-API文档-中文版.zip

    赠送jar包:validation-api-2.0.1.Final.jar; 赠送原API文档:validation-api-2.0.1.Final-javadoc.jar; 赠送源代码:validation-api-2.0.1.Final-sources.jar; 赠送Maven依赖信息文件:validation-api-2.0.1....

    validation-api-2.0.1.Final-API文档-中英对照版.zip

    赠送jar包:validation-api-2.0.1.Final.jar; 赠送原API文档:validation-api-2.0.1.Final-javadoc.jar; 赠送源代码:validation-api-2.0.1.Final-sources.jar; 赠送Maven依赖信息文件:validation-api-2.0.1....

    FormValidation完整源码和演示

    FormValidation是一款功能强大的前端表单验证框架,专为开发者提供高效、灵活的验证解决方案。它以其高度可定制性,对HTML data属性的完美支持以及内置的自定义验证器功能而备受推崇。本资源包含了FormValidation的...

    jakarta.validation-api-2.0.1-API文档-中文版.zip

    赠送jar包:jakarta.validation-api-2.0.1.jar; 赠送原API文档:jakarta.validation-api-2.0.1-javadoc.jar; 赠送源代码:jakarta.validation-api-2.0.1-sources.jar; 赠送Maven依赖信息文件:jakarta.validation...

    jakarta.validation-api-2.0.1-API文档-中英对照版.zip

    赠送jar包:jakarta.validation-api-2.0.1.jar; 赠送原API文档:jakarta.validation-api-2.0.1-javadoc.jar; 赠送源代码:jakarta.validation-api-2.0.1-sources.jar; 赠送Maven依赖信息文件:jakarta.validation...

    Validation3个jia包 validation-api,hibernate-validator

    `Validation`是Java世界中用于验证对象的有效性的一种机制,它使得我们可以方便地定义和执行数据验证规则。在给定的标题和描述中提到了三个重要的JAR包:`validation-api`, `hibernate-validator`以及`jboss-logging...

    FormValidation.js

    **FormValidation.js 知识点详解** `FormValidation.js` 是一个强大且灵活的JavaScript库,专门用于前端表单验证。它提供了丰富的校验规则、样式定制以及对动态添加元素的验证支持,使得开发者能够轻松地创建高效、...

    使用FormValidation进行表单验证

    `FormValidation`是一个强大的JavaScript库,它结合了`jQuery`和`Bootstrap`框架,使得表单验证变得更加简单易用。本文将详细介绍如何使用`FormValidation`进行表单验证,并探讨与`jQuery`和`Bootstrap`的集成。 ...

    validation后端验证所需要jar包

    "validation后端验证所需要jar包"主要指的是用于进行后端参数验证的一系列Java库,这些库通常包含了对实体类、对象、列表以及映射等数据结构的有效性检查功能。在描述中提到的功能,如检查是否为空、是否为空字符串...

    javax.validation-1.0.0.GA.jar

    "javax.validation-1.0.0.GA.jar"是一个关键的组件,它提供了Java约束验证API,是Java Bean Validation规范的实现,允许开发者在业务逻辑层对输入数据进行验证。 Java Bean Validation(JSR 303)是一种标准,定义...

    easyexcel+validation excel导入导出下载

    EasyExcel是一款由阿里巴巴开发的轻量级Java库,专门用于处理Excel数据的读写操作,而Validation则是用于数据验证的一种机制。本文将深入探讨如何结合EasyExcel和Validation实现高效且准确的Excel导入导出与数据校验...

    jQuery Validation Engine ( jQuery 表单验证插件)

    jQuery Validation Engine是一款强大的JavaScript库,专门用于实现网页表单的验证功能。它是基于流行的JavaScript库jQuery构建的,为开发者提供了一种优雅的方式来处理用户输入的数据验证。这个插件以其高度可定制性...

    jQuery-validation-1.14.0 官方源代码(2015.09.13)

    《jQuery-validation-1.14.0:前端验证利器详解》 jQuery-validation 是一个广泛使用的JavaScript库,专门用于实现前端表单验证。1.14.0版本在2015年9月13日发布,它提供了强大的功能,帮助开发者轻松地创建具有...

    validation-api-1.1.0.Final.jar

    Bean Validation API.release版本 JSR-303 是JAVA EE 6 中的一项子规范,叫做Bean Validation,现在一共有两个规范:BeanValidation1.0(即JSR303)和BeanValidation1.1(即JSR349),主要用于对数据进行校验,确保输入进来...

    FormValidation.rar

    《FormValidation:高效表单验证的利器》 在Web开发中,表单验证是一个不可或缺的环节,它确保了用户输入的数据符合预设的规范,从而维护数据的完整性和安全性。"FormValidation"是一款专为此目的设计的强大工具,...

    jQuery-validation.rar

    jQuery-validation是一个广泛使用的JavaScript库,专门用于实现网页表单的验证功能。这个插件使得开发者能够轻松地添加各种验证规则,提升用户体验,确保用户在提交表单前输入的数据符合预设的标准。它通过简单的API...

    Bean Validation 规范文档

    《Bean Validation规范详解》 Bean Validation是Java平台上用于对象验证的一种标准,旨在提供一种简单而强大的方式来确保Java Bean对象的正确性和完整性。本规范文档深入解析了Bean Validation的各个方面,包括其...

    jquery-validation-1.13.0

    **jQuery Validation Plugin 1.13.0 知识点详解** jQuery Validation Plugin 是一个流行的JavaScript库,专门用于实现Web表单的数据验证。这个插件是基于jQuery框架设计的,因此,它能够轻松地与jQuery的其他功能...

Global site tag (gtag.js) - Google Analytics