Bogdan Popa
Bogdan Popa

Reputation: 1099

How can I validate a field to include only letters?

Let's say I have a 'city' or 'country' input field. How can I validate this field to only include letter?

Currently I am replacing any eventual numeric character with a blank space like this:

def strip_numeric_characters
  self.city = self.city.gsub(/[0-9]/, "")
  self.country = self.country.gsub(/[0-9]/, "")
end

But it's not the right way, because if someone is inputting only numbers, I'll end up with en empty string.

Upvotes: 3

Views: 7198

Answers (1)

Sharvy Ahmed
Sharvy Ahmed

Reputation: 7405

You can validate attribute format using validates_format_of like this:

validates_format_of :city, :country, :with => /^[a-z]+$/i

/^[a-z]+$/i will only allow city and country names with letters only. The following is the details of the regex.

^     => Start of line
[a-z] => Any single character in the range a-z
+     => One or more characters of the range
$     => End of line
i     => To make case insensitive

Upvotes: 10

Related Questions