]> git.openstreetmap.org Git - rails.git/blobdiff - app/validators/normalized_uniqueness_validator.rb
Require user names to be unique after unicode normalisation
[rails.git] / app / validators / normalized_uniqueness_validator.rb
diff --git a/app/validators/normalized_uniqueness_validator.rb b/app/validators/normalized_uniqueness_validator.rb
new file mode 100644 (file)
index 0000000..eb3600c
--- /dev/null
@@ -0,0 +1,18 @@
+class NormalizedUniquenessValidator < ActiveModel::EachValidator
+  def validate_each(record, attribute, value)
+    relation = if options.fetch(:case_sensitive, true)
+                 record.class.where("NORMALIZE(#{attribute}, NFKC) = NORMALIZE(?, NFKC)", value)
+               else
+                 record.class.where("LOWER(NORMALIZE(#{attribute}, NFKC)) = LOWER(NORMALIZE(?, NFKC))", value)
+               end
+
+    relation = relation.where.not(record.class.primary_key => [record.id_in_database]) if record.persisted?
+
+    if relation.exists?
+      error_options = options.except(:case_sensitive)
+      error_options[:value] = value
+
+      record.errors.add(attribute, :taken, **error_options)
+    end
+  end
+end