Shruthi R
Shruthi R

Reputation: 1923

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.

Upvotes: 0

Views: 1845

Answers (3)

Chaudhary Prakash
Chaudhary Prakash

Reputation: 330

try this regex

^[a-zA-Z0-9\. /'\-]+$

Hope this will help

Upvotes: 0

Devd
Devd

Reputation: 343

  • Try this:

    /^[a-zA-Z\d\.\-\/# ]+$/
    

Upvotes: 0

Lahiru Jayaratne
Lahiru Jayaratne

Reputation: 1762

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.

Upvotes: 3

Related Questions