0
votes

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:

  1. The field should only ever contain numbers, non-numerical characters should not be valid.
  2. The field is allowed a maximum of one decimal point with a step of 0.5

For example:

  • "40" should be valid
  • "37.5" should be valid
  • "40 Hours" should be invalid
  • "32.3" should be invalid
  • "37.55" should be invalid
  • "37..5" should be invalid

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.

1

1 Answers

2
votes

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.