From 9407c7a94dbf363cb5f4469df905167edd5f7a2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A2u=20Cao?= Date: Sun, 19 Feb 2023 12:04:24 +0800 Subject: [PATCH] Add username format restrictions --- app/models/user.rb | 7 +++++++ spec/features/signup_spec.rb | 6 ++++++ 2 files changed, 13 insertions(+) diff --git a/app/models/user.rb b/app/models/user.rb index 40d5f20..4f49b81 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -12,6 +12,13 @@ class User < ApplicationRecord validates_uniqueness_of :cn validates_length_of :cn, :minimum => 3 + validates_format_of :cn, with: /\A([a-z0-9\-])*\z/, + if: Proc.new{ |u| u.cn.present? }, + message: "is invalid. Please use only letters, numbers and -" + validates_format_of :cn, without: /\A-/, + if: Proc.new{ |u| u.cn.present? }, + message: "is invalid. Usernames need to start with a letter." + validates_uniqueness_of :email validates :email, email: true diff --git a/spec/features/signup_spec.rb b/spec/features/signup_spec.rb index 8b730c2..9dff0df 100644 --- a/spec/features/signup_spec.rb +++ b/spec/features/signup_spec.rb @@ -71,6 +71,12 @@ RSpec.describe "Signup", type: :feature do fill_in "user_cn", with: "t" click_button "Continue" expect(page).to have_content("Username is too short") + fill_in "user_cn", with: "-tony" + click_button "Continue" + expect(page).to have_content("Username is invalid") + fill_in "user_cn", with: "$atoshi" + click_button "Continue" + expect(page).to have_content("Username is invalid") fill_in "user_cn", with: "jimmy" click_button "Continue" expect(page).to have_content("Username has already been taken")