lib/scrivener/validations.rb in scrivener-0.0.2 vs lib/scrivener/validations.rb in scrivener-0.0.3
- old
+ new
@@ -5,10 +5,15 @@
#
# * assert
# * assert_present
# * assert_format
# * assert_numeric
+ # * assert_url
+ # * assert_email
+ # * assert_member
+ # * assert_length
+ # * assert_decimal
#
# The core tenets that Scrivener::Validations advocates can be summed up in a
# few bullet points:
#
# 1. Validations are much simpler and better done using composition rather
@@ -119,14 +124,52 @@
# @param [Array<Symbol, Symbol>] error The error that should be returned
# when the validation fails.
# @see http://cyx.github.com/ohm-contrib/doc/Ohm/NumberValidations.html
def assert_numeric(att, error = [att, :not_numeric])
if assert_present(att, error)
- assert_format(att, /^\d+$/, error)
+ assert_format(att, /\A\d+\z/, error)
end
end
+ URL = /\A(http|https):\/\/([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}|(2
+ 5[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}
+ |localhost)(:[0-9]{1,5})?(\/.*)?\z/ix
+
+ def assert_url(att, error = [att, :not_url])
+ if assert_present(att, error)
+ assert_format(att, URL, error)
+ end
+ end
+
+ EMAIL = /\A([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*
+ [\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@
+ ((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+
+ [a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)\z/ix
+
+ def assert_email(att, error = [att, :not_email])
+ if assert_present(att, error)
+ assert_format(att, EMAIL, error)
+ end
+ end
+
+ def assert_member(att, set, err = [att, :not_valid])
+ assert(set.include?(send(att)), err)
+ end
+
+ def assert_length(att, range, error = [att, :not_in_range])
+ if assert_present(att, error)
+ val = send(att).to_s
+ assert range.include?(val.length), error
+ end
+ end
+
+ DECIMAL = /\A(\d+)?(\.\d+)?\z/
+
+ def assert_decimal(att, error = [att, :not_decimal])
+ assert_format att, DECIMAL, error
+ end
+
# The grand daddy of all assertions. If you want to build custom
# assertions, or even quick and dirty ones, you can simply use this method.
#
# @example
#
@@ -147,6 +190,5 @@
def assert(value, error)
value or errors[error.first].push(error.last) && false
end
end
end
-