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>
To validate the form using HTML, we will use HTML <input> required attribute. The <input> required attribute is a Boolean attribute that is used to specify the input element must be filled out before submitting the Form.
The list attribute of the input element is used to bind it together with a datalist element.
Using HTML5, we can create a form with built in validation (i.e. no javascript required). Earlier, we were using JAVASCRIPT to control form validation.
The datalist tag is introduced in HTML5. The <datalist> tag should be used with an <input< element that contains a "list" attribute. The value of "list" attribute is linked with the datalist id.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With