Validates_uniqueness_of only if present


#1

Hi - I want to allow duplicate fields values if the field is blank,
but disallow duplicates if it’s not. Is there a
validates_uniqueness_of_if_present equivalent?

Thanks,
Dino


#2

You can use :allow_nil or :allow_blank attributes to it like

validates_uniqueness_of :email, :allow_nil => true

this would skip the validation if field is nil.
:allow_blank works same way on empty strings.

And then all/most validations com with the :if and :unless options
that would allow for more detailed determination if the validation
should be used


#3

dino d. wrote:

Hi - I want to allow duplicate fields values if the field is blank,
but disallow duplicates if it’s not. Is there a
validates_uniqueness_of_if_present equivalent?

Thanks,
Dino

Hi,
As you required to place duplicate value if field is blank than you
just use
validates_uniqueness_of :field_name,:allow_blank => ‘true’

:allow_nil - If set to true, skips this validation if the attribute
is nil (default is false).

:allow_blank - If set to true, skips this validation if the attribute
is blank (default is false).