1

I have a select element like this:

<select name="select">
<option value="opt1">Select One Value Only</option>
<option value="opt2">Type 2</option>
<option value="opt3">Type 3</option>
</select>

and I want user to select a option e.g. opt2, opt3... but opt1, how to to use html 5 validation to valid the select?

3 Answers 3

1

I think the only way to add the validation here is to set the default option value to an empty string and add required attribute to select element. Now you can click on submit button to see the validation:

<form>
  <label >Choose an option:</label>
  <select name="select" required>
    <option value="" disabled selected>Select One Value Only</option>
    <option value="opt2">Type 2</option>
    <option value="opt3">Type 3</option>
  </select>
  <input type="submit">
</form>

The issue here is that when you set a value to the default option to something other than empty string the validation infers it as a valid value has been already selected, thus the validation is not triggered at that point.

Sign up to request clarification or add additional context in comments.

Comments

1

You can do something like the following:

<select name="select">
  <option value="opt1" selected disabled>Select One Value Only</option>
  <option value="opt2">Type 2</option>
  <option value="opt3">Type 3</option>
</select>

In the snippet above, the opt1 is selected by default. The user can only select opt2 or opt3, but once they do that then they cannot selecte opt1, hope this is the behaviour you're looking for.

3 Comments

Thanks for the quick answer, if a user does not select anything, the opt1 would be seleced, this is not expected.
I've updated my answer, removed the value="opt1" by accident.
How to remind the users to select opt2 or the other options if they forget to select a option in the selector? Essentially, I want to use html5 validation to do this, but I do not know how to custom it.
1

Try Using:

<select name="select" required>
  <option value="opt1" selected="selected" disabled>Select One Value Only</option>
  <option value="opt2">Type 2</option>
  <option value="opt3">Type 3</option>
</select>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.