Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Required validation not working in form

The "required" validation is working for form

<!DOCTYPE html>
<html>
<body>
<form action=''>
<select required>
  <option value="">None</option>
  <option value="volvo">Volvo</option>
  <option value="saab" >Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
<input type="submit">
</form>
</body>
</html>

but is not working for the same form if I move the option with empty value down the list.

<!DOCTYPE html>
<html>
<body>
<form action=''>
<select required>
  <option value="volvo">Volvo</option>
  <option value="saab" >Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
  <option value="">None</option>
</select>
<input type="submit">
</form>
</body>
</html>

Why? How exactly does the select element validation work?

Referred to the following: https://www.w3schools.com/tags/att_select_required.asp

like image 643
Dhruv Ishpuniani Avatar asked Aug 08 '18 11:08

Dhruv Ishpuniani


People also ask

Why required is not working in select tag?

The required attribute is there in the HTML select element. If it is not working for you, then try checking back the “first value” field. You need an empty value there.

Can we use required in select tag?

The required attribute of the <select> element is to let users know that the <select> drop-down is required and need to be submitted before the form is submitted. If you won't select the value from the drop-down and try to submit the form, it won't submit and a warning would be visible on the web page itself.

How do you add validation to a form?

The simplest HTML validation feature is the required attribute. To make an input mandatory, add this attribute to the element. When this attribute is set, the element matches the :required UI pseudo-class and the form won't submit, displaying an error message on submission when the input is empty.


1 Answers

The following is from w3 docs:

The required attribute is a boolean attribute. When specified, the user will be required to select a value before submitting the form.

...

if the value of the first option element in the select element's list of options (if any) is the empty string

...

Which means that the required attribute works only if the value of the first element is empty

like image 153
YouneL Avatar answered Sep 28 '22 01:09

YouneL