Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation only in specific form

Is there any way to trigger validation only in specific forms(controller's action), not globally at every save or update? Something like User.create(:validate=>true) flag.

like image 208
methyl Avatar asked Sep 25 '11 13:09

methyl


People also ask

What are different types of form validation?

In general, there are two main types of form validation: After submit validation. Inline validation.

What is inline form validation?

In short, inline validation is an effort on behalf of the form to help users correct information as they go, ideally so that when the point comes to submit the form, they are more likely to submit it on the first attempt. The more failed attempts a user makes to submit the form, the more likely they are to give up.

How do you add validation to a form?

The simplest HTML validation feature is the required attribute. To make an input mandatory, add this attribute to the element. When this attribute is set, the element matches the :required UI pseudo-class and the form won't submit, displaying an error message on submission when the input is empty.

How do I disable default form validation?

If You want to disable the validation for all elements of the form add the novalidate attribute in the form tag which will disable the validation for entire form.


2 Answers

Yes, you can supply conditionals to the validations, eg:

validates_presence_of :something, :if => :special?

private

def make_sepcial
  @special = true
end

def special?
  @special
end

Now all you have to do to turn on these validations is:

s = SomeModel.new
s.make_special
like image 76
thomasfedb Avatar answered Sep 21 '22 15:09

thomasfedb


As you explained in the comments, you want to skip validation for new records. In that case, you can use thomasfedb's answer, but don't use the @special variable, but:

validates_presence_of :something, :if => :persisted?

This will validate only for saved Users, but not for new Users. See the API documentation on persisted?.

like image 22
rdvdijk Avatar answered Sep 24 '22 15:09

rdvdijk