Rebirth
Rebirth

Reputation: 1011

Validation with regex fails while it shouldn't

validates_format_of         :start_time,    :with => /\A\d{2}:{1}\d{2}\z/ 

This is supposed to validate the start time with a format of 00:00, yet whatever I throw at it, it validates as false thus doesn't let me update the attribute.

What am I missing here?

Somehow the line above also inhibits me from updating other attributes too. Removing the line solves all problems and lets me update any attribute again.

The code that updates the attribute is:

if current_restaurant.update(params.require(:restaurant).permit(:start_time))
    //success handling
else 
    //failure handling
end

Upon further inspection the params consist of:

{"utf8"=>"✓", 
    "restaurant"=>
        {"start_time"=>"00:00"}, 
         "action"=>"update", 
         "controller"=>"restaurants"}

Upvotes: 0

Views: 89

Answers (1)

Rebirth
Rebirth

Reputation: 1011

I think the key problem in my question was:

Somehow the line above also inhibits me from updating other attributes too. Removing the line solves all problems and lets me update any attribute again.

Therefore I tried allowing for blank in combination with a regex, which happens to fix my problem!

Solution:

validates_format_of    :start_time,    :with           => /\A\d{2}:{1}\d{2}\z/ ,
                                       :allow_blank    => true

edit: a better regex for time_validation would be:

/\A([01][0-9]|2[0-3]):[0-5][0-9]\z/

Upvotes: 3

Related Questions