Jeffrey Wen
Jeffrey Wen

Reputation: 617

Rails 5 - jQuery validate on form.select only works after submitting

I have a drop-down that I need to validate, but it is not behaving like I expect it to.

# app/views/forms/_form.html.erb

<%= form.select :environment, [ 'Production', 'Staging', 'Test' ],
{ prompt: 'Select an Environment' }, { required: true } %>


# app/assets/javascripts/forms.js
$('form#new_form').validate({
  validClass: "valid",
  errorClass: "invalid",
    rules: {
      'form[environment]': { required: true },
    }
});

Steps to reproduce:

  1. Click on the drop-down
  2. Select an option; Production, Staging, or Test
  3. The valid class gets added to the drop-down
  4. -- This is where the issue occurs -- Click back on the drop-down list and select the prompt Select an Environment.
  5. The invalid class does not get added to the drop-down.

The above steps only work as expected when I submit the form and watch it error out. Then, when I repeat steps 1-5, the valid class gets added when I select an option (Production, Staging, or Test), and the invalid class gets added when I select the prompt Select an Environment

Upvotes: 1

Views: 456

Answers (1)

kolas
kolas

Reputation: 754

According to docs (https://jqueryvalidation.org/documentation/) it behaves like expected.

Before a field is marked as invalid, the validation is lazy: Before submitting the form for the first time, the user can tab through fields without getting annoying messages – they won't get bugged before having the chance to actually enter a correct value

Once a field is marked invalid, it is eagerly validated: As soon as the user has entered the necessary value, the error message is removed

Upvotes: 1

Related Questions