Shruthi R Shruthi R - 4 months ago 28
Ruby Question

Rails - Alphanumeric field validation

In rails 4, I need to validate the alphanumeric field which can accept only dot(.), hyphen(-), slash(/) and space in between the characters.

Eg:

AB123-GH345
or
AB45.NH744
or
KHJ3/SD34
or
HJS23 JKA34


I have tried with
/^[0-9]+#$/
and
/^\d+([.,]\d+)?$/
and
/^[0-9]+#$/
but it is not working as per the requirement.

Value should be accept as per the examples. Please help me to validate this field.

Answer

I think this might help you:

/^[A-Za-z0-9-\/\.\s]+$/

This worked for all the examples you have provided

AB123-GH345 or AB45.NH744 or KHJ3/SD34 or HJS23 JKA34

and rejected when I inserted a character like ? in the middle(HJS23?JKA34).


Update

If you don't want multiline anchors then you can use it like this:

/\A[A-Za-z0-9-\/\.\s]+\z/

You can use this Rubular site to validate your Regex codes.