existing_username_validator.rb 1003 B

12345678910111213141516171819202122232425262728
  1. # frozen_string_literal: true
  2. class ExistingUsernameValidator < ActiveModel::EachValidator
  3. def validate_each(record, attribute, value)
  4. return if value.blank?
  5. usernames_and_domains = begin
  6. value.split(',').map do |str|
  7. username, domain = str.strip.gsub(/\A@/, '').split('@', 2)
  8. domain = nil if TagManager.instance.local_domain?(domain)
  9. next if username.blank?
  10. [str, username, domain]
  11. end.compact
  12. end
  13. usernames_with_no_accounts = usernames_and_domains.filter_map do |(str, username, domain)|
  14. str unless Account.find_remote(username, domain)
  15. end
  16. if options[:multiple]
  17. record.errors.add(attribute, I18n.t('existing_username_validator.not_found_multiple', usernames: usernames_with_no_accounts.join(', '))) if usernames_with_no_accounts.any?
  18. elsif usernames_with_no_accounts.any? || usernames_and_domains.size > 1
  19. record.errors.add(attribute, I18n.t('existing_username_validator.not_found'))
  20. end
  21. end
  22. end