existing_username_validator.rb 972 B

1234567891011121314151617181920212223242526
  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 = value.split(',').filter_map do |str|
  6. username, domain = str.strip.gsub(/\A@/, '').split('@', 2)
  7. domain = nil if TagManager.instance.local_domain?(domain)
  8. next if username.blank?
  9. [str, username, domain]
  10. end
  11. usernames_with_no_accounts = usernames_and_domains.filter_map do |(str, username, domain)|
  12. str unless Account.find_remote(username, domain)
  13. end
  14. if options[:multiple]
  15. record.errors.add(attribute, I18n.t('existing_username_validator.not_found_multiple', usernames: usernames_with_no_accounts.join(', '))) if usernames_with_no_accounts.any?
  16. elsif usernames_with_no_accounts.any? || usernames_and_domains.size > 1
  17. record.errors.add(attribute, I18n.t('existing_username_validator.not_found'))
  18. end
  19. end
  20. end