Validation of encrypted data

1.4k Views Asked by At

I encrypt all private data of users before storing in database with help of gem 'attr_encrypted'. For example, I have 'email_addresses' table, which contains 'encrypted_email' column. This gem decrypt data when I call object.email or when I search by emails. But I have issues with validation of this column.

I have following validations for this and other tables:

validates_length_of :email, :within => 3..100
validates_numericality_of :post_code

I should decrypt data before validation somehow, but I don't know how to do this with help of built-in Rails tools. I don't want invent custom validations for this. Please, advise.

1

There are 1 best solutions below

1
On

validations that doesn't need a db query run on the rails side so you can pass a method instead of a column to the validation methods

validates :decrypted_email, length: { within: 3..100 }

def decrypted_email
  # decrypt email here
end