Reputation: 1527
I want to check whether input from user can be converted to date. If not, there should be an alert that specified value should be date. Please help me to edit my controller (elsif part).
My input text field:
= text_field_tag :from, '', as: :string, class: 'datepicker form-control', placeholder: "From", label: false
= text_field_tag :to, '', as: :string, class: 'datepicker form-control', placeholder: "To", label: false
Controller:
def recalculate
from, to = params[:from], params[:to]
if from.empty? || to.empty?
redirect_to tarriff_path(@tarriff), alert: "Can't be empty"
elsif ???
redirect_to tarriff_path(@tarriff), alert: "Should be date"
else
...
redirect_to tarriff_path(@tarriff), notice: "Was recalculated"
end
end
Upvotes: 1
Views: 70
Reputation: 426
Create a new method to parse your date values and return either a true or false to keep your code reasonably clean.
require 'date'
def recalculate
from, to = params[:from], params[:to]
if from.empty? || to.empty?
redirect_to tarriff_path(@tarriff), alert: "Can't be empty"
elsif valid_date?(from) && valid_date(to)
redirect_to tarriff_path(@tarriff), alert: "Should be date"
else
...
redirect_to tarriff_path(@tarriff), notice: "Was recalculated"
end
end
def valid_date(date)
Date.parse(date.to_s) rescue nil ? true : false
end
Upvotes: 0
Reputation: 111
You can use Date.parse
def is_valid_date(value)
Date.parse(value) rescue false
end
if is_valid_date(from) && is_valid_date(to)
[..]
end
Documentation here Date#parse
Hope it can help.
Upvotes: 4