I'm an Elixir beginner.
I am trying to validate a field for employee working hours. I have an input with an attribute of type="number"
, however this attribute does not fully work for Internet Explorer 11 so I need back end validation to have browser compatability.
The requirements are:
For example:
Here's all I got so far:
defp validate_working_hours(changeset) do
changeset
|> Changeset.validate_number(:working_hours, greater_than: 0)
end
How would I go about validating my requirements? I presume validate_format
would come in useful here - something along the lines of
|> Changeset.validate_format(:working_hours, <something here>)
But after fiddling around I can't seem to validate these requirements. Any help appreciated, cheers.
You are after Ecto.Changeset.validate_format/4
...
|> validate_format(:working_hours, ~r/^\d+(?:\.[05])?$/)
This regular expression means at least one digit, followed by an optional dot with either zero or five.
Sidenote: please note, that if you ever suppose making this application to be used worldwide, many countries use e. g. the comma (,
) for decimal separator and the code must be more cumbersome involving locales.