Bogdan Popa
Bogdan Popa

Reputation: 1099

Clear rails input field content if validation fails

I want to display error messages inside my input fields so I'm doing this by placing them inside the placeholder:

<%= f.input :age, label: false, placeholder: "#{f.object.errors.messages.has_key?(:age) ? f.object.errors.messages[:age].join(", ") : "Age*"}" %>

This is my model validation for age:

validates :age, numericality: { greater_than_or_equal_to: 18 }

However, if I submit age with value 11, I will have a red bordered input field with the value 11. How can I clear the input field if validation fails to pass?

I tried with a custom validation method, something like:

  validate :minimum_age

  def minimum_age
    if age < 18
      self.errors.add(:age, "must be at least 18 years old!")
      self.age = nil
    end
  end

This will clear the field, but when it renders the view, I'll also have a 'field must not be empty' error, because I just made it nil.

Upvotes: 1

Views: 1759

Answers (4)

Wayne Chu
Wayne Chu

Reputation: 308

Try

<%= f.input :age, label: false, placeholder: "your code", value: nil %>

By the way, you might want to extract your placeholder message into helper method, it's little mess now, lol

Like:

def render_error_message(f, key)
  f.object.errors.messages.has_key?(key) ? f.object.errors.messages[:age].join(", ") : "Age*"}
end

Then in your view:

<%= f.input :age, label: false, placeholder: render_error_message(f, :age), value: nil %>

Upvotes: 1

Sandip Ransing
Sandip Ransing

Reputation: 7733

This is a very awkward requirement you have; still if you want to clear the value then I would suggest do it in view instead of model or you may choose to do it using JS.

Upvotes: 0

fphilipe
fphilipe

Reputation: 10054

You could just clear that field if it has errors:

unless @user.valid?
  @user.age = nil if @user.errors.include?(:age)
end

Upvotes: 1

Bogdan Popa
Bogdan Popa

Reputation: 1099

Managed to do it by setting f.object.age = ""

<%= f.input :age, label: false, placeholder: "#{f.object.errors.messages.has_key?(:age) ? "#{f.object.age = ""}Vârstă*" + " " + "( #{f.object.errors.messages[:age].join(", ")} )" : "Vârstă*"}" %>

Upvotes: 0

Related Questions