2

I am new with rails and I am trying to register my user's names without special characters and spaces but allowing the - symbol.

Example : 
@@Pierre! => invalid
Pierre-Louis => valid
Pierre Louis => invalid

In the User.rb file I have :

class User < ApplicationRecord
...
validates :first_name, presence: true, length: {maximum: 25}, format: {with: Regexp.new('[^0-9A-Za-z-]')}
...

I don't have any error message and I'm still able to register using special characters.

Also, I'd like to add an error message if the name isn't validated.

Do you have any leads ?

Any help would be much appreciated !

1 Answer 1

1

When you validate format with regex, you need to ensure you match the whole string that is being validated. In order to do that your regex needs to start with \A and end with \z that are anchors marking beginning and ending of the string.

In your case:

validates :first_name, 
  presence: true, 
  length: {maximum: 25}, 
  format: {with: /\A[-0-9A-Za-z]\z'/}
  message: "Custom message"

assuming you accept numbers, small and big letters and a minus sign.

Sign up to request clarification or add additional context in comments.

1 Comment

With :message option: edgeguides.rubyonrails.org/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.