ivan
ivan

Reputation: 6322

simple_form validation with non-ActiveRecord model not working right

I'm using simple_form with a vanilla Ruby model that's not stored in the database. It's a helper model that interacts with a model that is in the db. I'm able to use simple_form_for with a symbol rather than an instance (simple_form_for :vanilla_model), but running into a problem with client-side validation (HTML5 required attribute).

My form has a select box and some radio-buttons. I go ahead and choose an option in each, and click 'submit'. Rather than submitting the form, the browser highlights (doesn't select, just focuses) the first radio-button, as it would if I'd failed to make a choice.

I can get around this by disabling the required attribute, but I'd actually like to use it. Here's my view:

= simple_form_for(:my_model, url: my_path, method: :post) do |f|
  = f.input_field :number, collection: numbers
  = f.input_field :color, collection: colors, as: :radio_buttons
  = f.button :submit

and the generated HTML

<form action="/my/path" class="simple_form my_model" method="post">
  <div>
    ... utf8 & authenticity token ...
  </div>

  <select class="select required" id="my_model_number" name="my_model[number]">
    <option value=""></option>
    <option value="1">1</option>
    <option value="2">2</option>
  </select>

  <span class="radio">
    <input class="radio_buttons required" id="my_model_color_red" name="my_model[color]" type="radio" value="red" />
    <label class="collection_radio_buttons" for="my_model_color_red">Red</label>
  </span>
  <span class="radio">
    <input class="radio_buttons required" id="my_model_color_blue" name="my_model[color]" type="radio" value="blue" />
    <label class="collection_radio_buttons" for="my_model_color_blue">Blue</label>
  </span>

  <input class="button" name="commit" type="submit" value="Submit" />
</form>

Can someone point out what I'm missing here? Should I just give up on trying to take advantage of the HTML5 validation and use jQuery? I'm using jQuery for some other parts of the page, so I could go that route, but I'd like to figure this out.

Upvotes: 1

Views: 937

Answers (1)

ruby_newbie
ruby_newbie

Reputation: 3285

It is generally bad practice to rely on HTML 5 validations because many browsers do not support them. Why not add the validations to your model to do it the rails way?

validates :color, inclusion: {in: ["red", "blue"]}

Upvotes: 3

Related Questions