How can i validate the input from a html5 Datalist?
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
You can do this with HTML5 validation using pattern
. It's easier if you're populating your datalist with some sort of template, but it would look something like this (Note that you would need additional code to handle the validation - I just added very simple CSS to display the validation state)
It's worth noting that this automatically blocks form submission and provides proper semantics for accessibility and other standards-compliant interoperability.
input:valid {
border: 1px solid green;
}
input:invalid {
border: 1px solid red;
}
<input type="text" list="colours"
pattern="^(Red|Blue|Green|Black|White)$"
>
<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>