1

I was trying to add a validation for an Empty Field. If field is empty, form will not be submitted. But my "required" attributes not working.

Birthdate: 
<select name="month" required>
<option value="0" required>Select Month</option>
    <?php
        for( $m = 1; $m <= 12; $m++ )
            {
                $num = str_pad( $m, 2, 0, STR_PAD_LEFT );
                $month = date( 'F', mktime( 0, 0, 0, $m + 1, 0, 0 ) );?>
                <option value="<?php echo $num;?>"><?php echo $month; ?></option>
                <?php
            }
    ?>
    </select>

</select>
  • 4
    Does this answer your question? [Does the select element have the required attribute?](https://stackoverflow.com/questions/8287353/does-the-select-element-have-the-required-attribute) – Sven Eberth May 31 '21 at 15:22
  • @SvenEberth I was trying to add a validation. If field is empty, form will not be submitted: –  May 31 '21 at 15:32
  • 3
    Did you read the accepted answer from the link @SvenEberth posted? Your first `value` should be empty for `required` to work – brombeer May 31 '21 at 15:41
  • Hello @ace_mbj you have to set one ` – Ankit Tiwari May 31 '21 at 16:28

3 Answers3

0

<option> does not need 'required', only in <select> is enough. if you want to get first one as default use 'selected' instead of 'required'.

Sven Eberth
  • 3,057
  • 12
  • 24
  • 29
0

Option tag does not have required attribute.

<select name="month" required>
<option value="0">Select Month</option>
    <?php
        for( $m = 1; $m <= 12; $m++ )
            {
                $num = str_pad( $m, 2, 0, STR_PAD_LEFT );
                $month = date( 'F', mktime( 0, 0, 0, $m + 1, 0, 0 ) );?>
                <option value="<?php echo $num;?>"><?php echo $month; ?></option>
                <?php
            }
    ?>
</select>

https://developer.mozilla.org/es/docs/Web/HTML/Element/option

0

You could unset value in the first option. Example:

<select name="month" required>
      <option value="" required>Select Month</option>
      <option value="1">January</option>
      <option value="2">February</option>
      <option value="3">March</option>
      <option value="4">...</option>
</select>
SzE
  • 23
  • 4