Reputation: 48453
I have registration that consist of 2 steps. In the first one, the new user will set up his name, email and password. Then he clicks on the "Sign Up" button and is redirected on the page where is the second part of the registration form (approx 5-7 fields).
I have set up validation rules on all inputs (7-10 fields). The problem is, when I fill out the first part of the form and then I click on the Sign Up button, I see validation errors, because the fields from the second part of the form are not valid.
How to avoid this behavior?
Thank you
Upvotes: 1
Views: 1042
Reputation: 38645
You can define a virtual attribute which will be used to determine which attributes to validate at which step, then use that attribute's value on with_options
to validate the required fields at each step.
Something like following:
In your Model:
class MyModal < ActiveRecord::Base
attr_accessor :validate_step
with_options if: :validate_step_one? do |o|
o.validates :name, presence: true
o.validates :email, presence: true
o.validates :password, presence: true
end
with_options if: :validate_step_two? do |o|
...
end
private:
def validate_step_one?
self.validate_step == 'validate_first_step'
end
def validate_step_two?
self.validate_step == 'validate_second_step'
end
end
Then in your Controller:
class MyRegistrationController < ApplicationController
def show
case step
when :first_step
user.validate_step = 'validate_first_step'
when :second_step
user.validate_step = 'validate_second_step'
end
end
end
In your controller, in the action where you build the object you need to assign either validate_first_step
or validate_second_step
based on the current step in your wizard.
Note that the values and names I've used are not very descriptive/meaningful, and you'd know much better how to name them :)
Upvotes: 1