简体   繁体   中英

Validation with datalist

I want to validate my input datalist so that it will only be submitted when one of the elements is selected from the list. If not submit then I want to give a red error message next to the input element so the user understands what he did wrong.

Example:

  <input type="text" list="typ" name="name" placeholder="gtown" > <datalist id="typ"> <select name="name"> <option value="atown">atown</option> <option value="btown">btown</option> <option value="ctown">ctown</option> </select> </datalist> </input> 

I wonder if it is possible with datalist?

If anyone can help me, I would be very grateful.

edit: I want to validate the code, it should now if it is on of the options or not, or when nothing was inputed, more like this answer I found Datalist option validation required however it give a pop up window, and I do not now how to show next to the input only a error message.

Edit2: I must not use an additional library.

You could do it by comparing the input's value with those you want to allow, as I've done in the code snippet below, but I think a simple <select> would be more appropriate than an input with a datalist if you want to give users a restricted list of options.

 let btn = document.getElementById("btnSend"); let form = document.getElementById("zeForm"); let input = document.getElementById("zeInput"); let msg = document.getElementById("msg"); let allowedValues = ["atown", "btown", "ctown"]; // same values as the options in your datalist btn.onclick = function() { let allGood = false; allowedValues.forEach(function(elm) { if(elm === input.value) { allGood = true; return; } }) if(allGood) { msg.innerHTML = "Success!!"; msg.style.color = "green"; //form.submit(); } else { msg.innerHTML = "This value is not accepted"; msg.style.color = "red"; } msg.style.display = "inline"; } 
 #msg { display: none; } #btnSend { display: block; margin-top:1rem; } 
 <form id="zeForm"> <input id="zeInput" type="text" list="typ" name="name" placeholder="gtown" > <datalist id="typ"> <!-- notice the absence of a <select> here... --> <option value="atown">atown</option> <option value="btown">btown</option> <option value="ctown">ctown</option> </datalist> </input> <p id="msg"></p> <button id="btnSend" type="button">send</button> </form> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM