module ActiveModel::Validations::HelperMethods
def validates_format_of(*attr_names)
+:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
There is also a list of default options supported by every validator:
beginning or end of the string. These anchors are ^ and $.
anchors that match the beginning or end of lines as opposed to the
* :multiline - Set to true if your regular expression contains
runtime.
a proc or lambda returning regular expression which will be called at
match will result in a successful validation. This can be provided as
* :without - Regular expression that if the attribute does not
lambda returning regular expression which will be called at runtime.
result in a successful validation. This can be provided as a proc or
* :with - Regular expression that if the attribute matches will
* :message - A custom error message (default is: "is invalid").
Configuration options:
else an exception will be raised.
In addition, both must be a regular expression or a proc or lambda, or
You must pass either :with or :without as an option.
using \A and \z.
anchors in the provided regular expression. In most cases, you should be
the multiline: true option in case you use any of these two
Due to frequent misuse of ^ and $, you need to pass
string, ^ and $ match the start/end of a line.
Note: use \A and \z to match the start and end of the
end
with: ->(person) { person.admin? ? /\A[a-z0-9][a-z0-9_\-]*\z/i : /\A[a-z][a-z0-9_\-]*\z/i }
validates_format_of :screen_name,
# Admin can have number as a first letter in their screen name
class Person < ActiveRecord::Base
expression that will be used to validate the attribute.
You can also provide a proc or lambda which will determine the regular
end
validates_format_of :email, without: /NOSPAM/
class Person < ActiveRecord::Base
match the regular expression:
Alternatively, you can require that the specified attribute does _not_
end
validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create
class Person < ActiveRecord::Base
attribute matches the regular expression:
form, going by the regular expression provided. You can require that the
Validates whether the value of the specified attribute is of the correct
def validates_format_of(*attr_names) validates_with FormatValidator, _merge_attributes(attr_names) end