when rails model is validated using regex for username field it creates conflicts with existing usernames who are already registered

when i validate username field using regex in rails models everything works locally but it fails in appveyor test for continuous integration my code is conflicting with existing users

currently username accepts any random input my regex pattern ristrict it only to alphabets underscores and spaces but it is failing in appveyor test

my code in users.rb is

validates :name, format: { with: /\A[a-zA-Z_ ]{2,30}\z/,
                         message: ":can contain only alphabets,underscores and spaces" }

validates :email, format: { with: /\b[A-Z0-9._%a-z-]+@(?:[A-Z0-9a-z-]+.)+[A-Za-z]{2,4}\z/ }

what will be possible solution so that i can apply desired validation on username field and also it does not make conflicts with existing users

1 answer

  • answered 2020-09-14 05:42 Salil

    You can use on option for the validates, assuming name can't be update once created.

    validates :name, 
              format: { with: /\A[a-zA-Z_ ]{2,30}\z/,
              message: ":can contain only alphabets,underscores and spaces" },
              on: :create