sanny Sin
sanny Sin

Reputation: 1555

Creating custom validator

I have validator, that validates one of fields on form. Field return value with class ActiveSupport::TimeWithZone

validate :begins_at_not_in_past

def begins_at_not_in_past
    return unless self.state == 'Scheduled'
    if self.begins_at != nil && self.begins_at < (Time.now - 1.hour)
       errors.add(:begins_at, 'Action cannot begin in past')
      false
    end

end

If validation fails it show me my error, however it does create new record in database even though data in form is not valid. Where did i make mistake?

Upvotes: 2

Views: 249

Answers (2)

Rahul Tapali
Rahul Tapali

Reputation: 10137

You should have following line. Otherwise it won't add error to object. So add following line with errors.add

validate :begins_at_not_in_past

def begins_at_not_in_past
  return unless self.state == 'Scheduled'
  if self.begins_at != nil && self.begins_at < (Time.now - 1.hour)
    errors.add(:begins_at, 'Action cannot begin in past')
    errors[:base] << 'Correct errors'  # Rails 2.3.X errors.add_to_base('msg')
    false
  end
end

In controller: #Validation will run only when you call valid? method

if obj.valid?
  #do something
else
  flash[:error] = obj.errors.full_messages.join('<br/>')
end

Upvotes: 4

Chris Piazza
Chris Piazza

Reputation: 251

In your model, try

validates :field_name, :begins_at_not_in_past => true

If you don't specify an acceptable return value from your validator the model may not consider it a failed validation.

Upvotes: 1

Related Questions