How would validate that I get a string like "MM5442" in ecto and store 5442?

for a column in some tables I am getting strings like “MM5442” or “ED3321”. So it is always some alpha prefix and some important number. The alpha prefix is unique per table and it is only relevant to store the the number as a integer. I am thinking of doing this in the changeset and I want be able to validate that the data is correct for the column ie that that prefix is correct for the table and that the rest is a integer. Do you think I should use a custom type for this? Or should I implement a function that validates that the string starts with the prefix for the table and strips it in the beginning? Should I consider stripping the prefixes before giving them to the changeset and only cast the number?

What do you think? Thanks for your time!

Have a look here for starters: Elixir Docs - Binaries, strings, and charlists

I only have a little time right now so I’ll need keep this fairly short.

If the prefix is always 2 characters you could do something like this:

iex(1)> myspliter = fn <<a::8, b::8, rest::binary>> -> {<<a, b>>, String.to_integer(rest)} end
#Function<7.126501267/1 in :erl_eval.expr/5>
iex(2)> myspliter.("MM5442")
{"MM", 5442}
iex(3)> myspliter.("ED3321")
{"ED", 3321}

I’m using an anonymous function in that example and returning a 2 tuple just to give you and idea of how you might compose something to do what you need. Of course, depending on your use case, you may have to go a lot farther than this crude example. You’d also need to be careful with making sure String.to_integer/1 is passed something that it can convert to an integer or it will raise etc.

Others might chime in with better examples etc., but that should get you on the right path.

1 Like