Pavel
Pavel

Reputation: 1974

Valid is false but errors empty

When I'm check if object is valid <%= current_user.contact.valid? %> it returns false. But <%= current_user.contact.errors.count %> return 0. I found solution that worked for some people but I'm not sure clearly that it's fine for me.

Validations for Contact

validates :RPNumber, :RPSerial, :RPNumber, :RPWho, :RPWhen, :RPDivisionCode,
            :Name, :RPDateBorn, :RPWhereBorn, :RPAddress, :RPFamilyStatus, :RPChild,
            :ZPNumber, :ZPWhereBorn, :ZPWhen, :ZPWhenEnd, :ZPWho, :GenderID, :ZPFIO, presence: true

  validates_format_of :ZPFIO, with: /^[a-zA-Z\s\-]*$/, message: 'ZPFIO'
  validates_format_of :Phone, with: /7\(\d+\)\d+/, message: 'Phone'
  validates_format_of :PhoneCode, with: /\d+/, message: 'PhoneCode'
  validates_format_of :PhoneNumber, with: /\d+/, message: 'PhoneNumber'
  validates_format_of :Web, with: /^(http|https)\:\/\/([a-z0-9][a-z0-9_-]*(?:.[a-z0-9][a-z0-9_-]*)+):?(d+)?\/?$/i, allow_blank: true, message: 'Web'
  validates_format_of :Mail, with: /^([0-9a-z]*([-|_]?[0-9a-z]+)*)(([-|_]?)\.([-|_]?)[0-9a-z]*([-|_]?[0-9a-z]+)+)*([-|_]?)@([0-9a-z]+([-]?[0-9a-z]+)*)(([-]?)\.([-]?)[0-9a-z]*([-]?[0-9a-z]+)+)*\.[a-z]{2,4}$/i, message: 'Mail'

Upvotes: 0

Views: 114

Answers (1)

Max Williams
Max Williams

Reputation: 32943

Every time you do current_user.contact you make a new contact object. So, what you're doing is this:

#make a new contact object and run validations on it
current_user.contact.valid?

#make a new contact object, which hasn't had validation run on it, then see if it has errors
current_user.contact.errors.count

Try this:

contact = current_user.contact
contact.valid?
contact.errors.count

Upvotes: 1

Related Questions