The Codesee The Codesee - 4 months ago 23
PHP Question

Make datalist required

I would like the user not to be able to submit a form unless they have selected something from the dropdown

datalist
which appears as they type. If they just typed something random, I don't want the form to be submitted.

If this isn't possible, would a better option to be to check if the typed text appears in the datalist when the user submits?

<form method="post">
<input type="text" list="browsers">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
<input type="submit" name="submit">
</form>

<?php
if(isset($_POST['submit']
// function to check if something from the datalist was clicked and NOT just typed
}else{
echo'Select something from the datalist!';
}


While I can set the
datalist
as required, this can easily be by-passed.

Answer

If you want to go with server side validation,

<form method="post">
    <input type="text" list="browsers" name="items" required>
    <datalist id="browsers" >
        <option value="Internet Explorer">
        <option value="Firefox">
        <option value="Chrome">
        <option value="Opera">
        <option value="Safari">
    </datalist>
    <input type="submit" name="submit">
</form>

<?php 
if(isset($_POST['submit']
   $check = array('Internet Explorer', 'Firefox', 'Chrome', 'Opera', 'Safari');

if(in_array($_POST['items'], $check)){
  // Code to be execute. 
} else{
   echo'Select something from the datalist!';
}

}else{
   echo'Select something from the datalist!';
}