comfycozy
comfycozy

Reputation: 139

Rails validation format for city, st

Trying to add a validation for a location to be in the format of city, state (ex. New York, NY) with the city being any length and the state being 2 characters. Found multiple resources to validate emails and specific file types, but can't get it right for city, state. Closest I came up with was for C#, but it's using ^ and $ and doesn't translate appropriately.

(^[\w\s]+,\s\w{2}$)

Upvotes: 0

Views: 298

Answers (2)

comfycozy
comfycozy

Reputation: 139

This is what worked for me:

/([A-Za-z]+(?: [A-Za-z]+)*),? ([A-Z]{2,2})/

Upvotes: 0

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10466

if 2 characters code can only be between a-z then use this:

^[^,]+,\s*[a-zA-Z]{2}$

otherwise you can use:

^[^,]+,\s*\w{2}$

Demo

Sample Source:

re = /^[^,]+,\s*\w{2}$/m
str = 'city, state 
New York, NY
Dhaka,DHK
California,Ca
Los Angeles, LA
'

# Print the match result
str.scan(re) do |match|
    puts match.to_s
end

Run the source code

Upvotes: 1

Related Questions