Commits

Michael Granger  committed 54367e5

Add :datetime builtin validator

  • Participants
  • Parent commits a12acfc

Comments (0)

Files changed (2)

File lib/strelka/paramvalidator.rb

 			:uri		  => /^(?<uri>#{URI::URI_REF})$/,
 			:uuid		  => /^(?<uuid>[[:xdigit:]]{8}(?:-[[:xdigit:]]{4}){3}-[[:xdigit:]]{12})$/i,
 			:date         => /.*\d.*/,
+			:datetime     => /.*\d.*/,
 			:json         => JSON_VALIDATOR_RE,
 			:md5sum       => /^(?<md5sum>[[:xdigit:]]{32})$/i,
 			:sha1sum      => /^(?<sha1sum>[[:xdigit:]]{40})$/i,
 		end
 
 
+		### Constrain a value to a parseable Date
+		def post_process_datetime( val )
+			return Time.parse( val )
+		rescue ArgumentError
+			return nil
+		end
+
+
 		### Constrain a value to a Float
 		def post_process_float( val )
 			return Float( val.to_s )

File spec/strelka/paramvalidator_spec.rb

 
 		end
 
+		describe ":datetime constaints" do
+
+			before( :each ) do
+				@validator.add( :expires, :datetime )
+			end
+
+			it "accepts dates" do
+				@validator.validate( 'expires' => '2008-11-18' )
+
+				@validator.should be_okay()
+				@validator.should_not have_errors()
+
+				@validator[:expires].should == Time.parse( '2008-11-18' )
+			end
+
+			it "accepts a date with a time" do
+				@validator.validate( 'expires' => '2008-11-18T12:31:18.818Z' )
+
+				@validator.should be_okay()
+				@validator.should_not have_errors()
+
+				@validator[:expires].should == Time.parse( '2008-11-18T12:31:18.818Z' )
+			end
+
+			it "rejects non-dates" do
+				@validator.validate( 'expires' => 'someday' )
+
+				@validator.should_not be_okay()
+				@validator.should have_errors()
+
+				@validator[:expires].should be_nil()
+			end
+
+		end
+
 		describe ":uri constraints" do
 			VALID_URIS = %w{
 				http://127.0.0.1