'How to limit the the input values for HTML to just values in a predefined list?
I need to deploy one of ML models as a web application. I am working to use HTML to get the input data and pass it to ML model for a live prediction. One of the inputs for this ML model is a 5 digit code. The code should be one of the predefined codes like one in this list [19827, 87198, 18288, ....], which contains 1000 unique values. The user should enter such a code. I want to tell the user whether the input code is valid or not. I am using the following line:
<input type="number" name="code" placeholder="code" min="10000" max="99999" step="1" pattern="\d+"/><br>
but this does not limit the input to the above list. For example, if user enter a code like 22222 and if that is not in the list the web app should tell the user that this is not valid. How can I do this one in a very efficient and professional way?
Solution 1:[1]
EDIT: Added javascript to load options.
You can use a datalist to limit what the user inputs, like this:
<label>Choose an ML code from this list:
<input list="codes" name="myCode" />
</label>
<datalist id="codes">
</datalist>
Javascript in the <head>
portion of the page loads options when the page loads:
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "codes.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("Code");
var options = "";
for (i = 0; i <x.length; i++) {
options += '<option value="' +
x[i].childNodes[0].nodeValue +
'">';
}
document.getElementById("codes").innerHTML = options;
}
document.onload(loadDoc);
</script>
In this example, you would have an XML data file in the same folder as the HTML file. Alternately, you could load the codes from a database. Doing so would require some server-side code written in a language such as C#, PHP, Python, etc.
Example codes.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<codes>
<code>19827</code>
<code>87198</code>
<code>18288</code>
<code>19555</code>
<code>21456</code>
<code>99874</code>
<!-- etc. -->
</codes>
As before, you would also need some additional javascript to validate the input.
Solution 2:[2]
You can't make this with HTML because HTML is a markup language. You should make this with PHP or python. in the frontend, you should make input static and in the backend, you can make this dynamic.
Code in python :
passcodes = ['1234' , '6523' , '8390'] #You can change this.
user_passcode = input("Enter your passcode: ")
if user_passcode in passcodes :
print("password is true")
else :
print("password is false")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |