Custom User Fields - Field Verification

Apologies for the lateness of the hour on this one - but for anyone scouring Meta to try and find out how to validate any custom fields you might’ve added, I thought it’d be worth mentioning how to do this with a plugin.

In your plugin.rb, use the validate method on User. You can then poke at your custom fields and set an error if any are invalid:

require_dependency 'user'

validate User, :my_cool_validation_method do
  field = self.custom_fields['cool_tapes']
  if ! field.blank? && field.include?("bag of four grapes")
    self.errors[:cool_tapes] << "No rhymes allowed."
  end
end

nb. the :my_cool_validation_method symbol can be anything you want, but should be unique within the context of the User model.

10 Likes