How do I validate a select field?

#1

Hi Guys,

I am using ParsleyJS to validate all my fields on the front-end but email is set to unique on the DB, so whenever an email that exists before is submitted again; my controller validator kicks in by sending the user back to the form informing the user that the email field is unique.

The problem though is that all my text fields return the data the user had filled in before but the select fields return empty so the user has to select those options they selected before server-side validation kicked in all over again.

Question:
How can I retain the options that were selected by the user before server validation?

This is a sample of what one of my select fields look like:

<div class="col-md-6 mg-b-30-f pt-xs-32">
  <label for="age_range">Age Range</label>
  <select class="form-control" name="age_range" id="age_range" required data-parsley-error-message="You have to specify your Age Range">
    <option label="Choose one"></option>
    <option value="Under 16">Under 16</option>
    <option value="16 - 20">16 - 20</option>
    <option value="21 - 30">21 - 30</option>
    <option value="Above 30">Above 30</option>
  </select>
  @if(hasErrorFor('age_range'))
      <small class="help-block error-messages">{{ getErrorFor('age_range') }}</small>
  @endif
</div>

Thanks and will really appreciate any assistance with this if you don’t mind @virk @romain.lanz @mezie @simonjcarr

0 Likes

#2

Hi guys,

I was able to address this with the old method, totally forgot that initially.

For anyone who will find this and you’re have this issue, this is the solution:

<option {{ old('age_range') == 'Under 16'? 'selected' : '' }} value = "Under 16">
    Under 16
</option>

Basically use a tenary to check what value Validator brings back, if it matches the value defined, append selected to the option and if not, do nothing.

Long live AdonisJS :grinning:

2 Likes

#3

I decided to share how to implement the same if you are fetching the values of the options from the DB.

Using the same codebase I had in my original post, we will assume the following:

  • We have an age_range table with the columns, id and age_range_label (id being the unique incrementing ID and age_range_label being “Under 16, 16 - 20 etc”)
  • That in our controller; age_range is passed into your view as a JSON object, therefore the code will be:
<select name="age_range">
  <option label="Choose One"></option>
     @each(age in age_range)
          <option value="{{ age.id }}" {{ old('age_range') == age.id ? 'selected' : '' }}> 
               {{ age.age_range_label }}
          </option>
     @endeach
</select>

Hope this helped

2 Likes