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
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.
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_-]*$".
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With