How can i validate the input from a html5 Datalist?

abaracedo picture abaracedo · Jul 24, 2014 · Viewed 14.9k times · Source

I would like to know how I can validate the input value that comes from a Datalist. I mean, if I have a Datalist where the user can start to write a value and then choosing it from the Datalist, but the user decides to don't choose any value from the list and he submits the form with the incomplete value, the sent value will be wrong.

I thought about iterate over all the elements of the Datalist but I think that it can't be a good idea if the Datalist has more than 1.000 values and I don't know any other way to validate it.

Here is an example of the Datalist that I'm going to use:

<input type="text" list="colours">

<datalist id="colours">
    <option value="Red" data-id="1">
    <option value="Blue" data-id="2">
    <option value="Green" data-id="3">
    <option value="Black" data-id="4">
    <option value="White" data-id="5">
</datalist>

Answer

nsthethunderbolt picture nsthethunderbolt · Jul 24, 2014

Try this:

<input type="text" list="colours" id='txt'>

And on form submit you can check:

var val = $("#txt").val();

var obj = $("#colours").find("option[value='" + val + "']");

if(obj != null && obj.length > 0)
    alert("valid");  // allow form submission
else
    alert("invalid"); // don't allow form submission