Search code examples
htmlsymfonyw3c

HTML5 validation in an auto generated Symfony2 form <select> field


I have the following code on a required select :

<select required="required">
    <option value="1">01</option>
    <option value="2">02</option>
    ...
    <option value="31">31</option>
</select>

In my (HTML5 / symfony2) app its a required date (day) so the value must be between 1 and 31 and I do not want blank/null values.

Even though the code works, it breaks w3c validation with the following error :

The first child option element of a select element with a required attribute and without a multiple attribute, and whose size is 1, must have either an empty value attribute, or must have no text content.

What is the best approach to the problem


Solution

  • With require attribute:

    <select required="required">
    <option value=""></option><!-- added empty value -->
    <option value="1">01</option>
    <option value="2">02</option>
    ...
    <option value="31">31</option>
    </select>
    

    Without – just remove require attribute:

    <select>
    <option value="1">01</option>
    <option value="2">02</option>
    ...
    <option value="31">31</option>
    </select>