Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate: Only letters, numbers and -

I would like to validate my users, so they can only use a-z and - in their username.

validates_format_of :username, :with => /[a-z]/

However this rule also allows spaces ._@

Username should use only letters, numbers, spaces, and .-_@ please.

Any ideas?

Best regards. Asbjørn Morell

like image 400
atmorell Avatar asked Jul 16 '09 07:07

atmorell


People also ask

How do you check if A string only has letters and numbers?

To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements. The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit.

How do I allow only letters and numbers in regex?

You can use regular expressions to achieve this task. In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".

How do you validate only letters in JavaScript?

You can write a JavaScript form validation script to check whether the required field(s) in the HTML form contains only letters. To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters.

How do you check if A string contains only the alphabet?

Regex can be used to check a string for alphabets. String. matches() method is used to check whether or not the string matches the given regex.


1 Answers

More complex solution but reusable and with more fine grained error messaging.

Custom validator:

app/validators/username_convention_validator.rb

class UsernameConventionValidator < ActiveModel::EachValidator
  def validate_each(record, field, value)
    unless value.blank?
      record.errors[field] << "is not alphanumeric (letters, numbers, underscores or periods)" unless value =~ /^[[:alnum:]._-]+$/
      record.errors[field] << "should start with a letter" unless value[0] =~ /[A-Za-z]/
      record.errors[field] << "contains illegal characters" unless value.ascii_only?
    end
  end
end

(Notice it does allow ' . - _ ' and doesnt allow non ascii, for completeness sake)

Usage:

app/models/user.rb

validates :name,
    :presence => true,
    :uniqueness => true,
    :username_convention => true
like image 126
laffuste Avatar answered Oct 06 '22 00:10

laffuste