Required fields

0
<label for=""><h5><strong>Dia da Semana</strong></h5></label>
<select name="Dia">
       <option value="0">Selecione o Dia</option>
        <?php
         $servername = "xxx.xxx.xx.xx";
$username = "xxxx";
$password = "xxxxxxx";
$dbname = "xxxxx";

$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset('utf8'); 

         $sql = "SELECT * FROM centrodb.DiasSemana ORDER BY Dias ASC";
         $qr = mysqli_query($conn, $sql);
         while($ln = mysqli_fetch_assoc($qr)){
            echo '<option value="'.$ln['Dias'].'">'.$ln['Dias'].'</option>';
         }
      ?>        
    </select>

I want this form field to be filled in

    
asked by anonymous 14.02.2018 / 18:22

3 answers

1

Make the logic that if it is empty or does not contain the expected data, show the message asking to fill in.

If html5 is to use

<input type="text" name="nome_do_campo" required>
    
14.02.2018 / 18:34
1

As I understood this your code, you wanted to say obligatory filling would be by the user and not by PHP. So let's understand the dynamically generated HTML of the options, even if they were static values.

You can check the option selected as ARRAY of SELECT using selectedIndex to identify the selected option.

Then Selecione o Dia is a filled-in value, so you'll need to validate with JAVASCRIPT:

function validarFormulario(){
	var myform = document.forms['formulario'] || document.formulario;
	if(myform.Dia.value == "0" || myform.Dia.selectedIndex == 0){
		alert('Preencha a data');
	}else{
		myform.submit();
	}
}
<form name="formulario" action="arquivo.php" method="POST">
<select name="Dia">
  <option value="0">Selecione...</option>
  <option value="2015">2015</option>
  <option value="2016">2016</option>
  <option value="2017">2017</option>
  <option value="2018">2018</option>
</select>
<input type="button" value="Enviar" onclick="validarFormulario()" />
</form>

You can also validate with PHP:

if($_SERVER['method'] === "POST"){
   if($_POST['Dia'] == "" || $_POST['Dia'] == null){
      /* Não Preenchido */
   }else{
      /* Preenchido */
   }
}
    
14.02.2018 / 19:19
0

If you want to use php only, I recommend it

After the <select> tag, you should see an error message saying it is wrong.

Use this code

<?php 
if(isset($_POST['botao_submit']) && $_POST['Dia'] != "")){
echo "Campo Obrigatório";
}
?>

With the above code it would check if the form had been submitted, if it had been submitted and the field was empty, it would appear that code.

Using required in select also results but if someone were Inspecionar Elemnto could well eliminate the required of the select and send it blank, with that code not.

    
14.02.2018 / 18:39