How can i validate the input from a html5 Datalist?

后端 未结 4 1321
遥遥无期
遥遥无期 2020-12-30 12:45

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

4条回答
  •  心在旅途
    2020-12-30 13:05

    If you use jQuery find method, it will traverse the DOM tree trying to find the correct element taking into account the value of one of its attributes, and looking at your comment, I think that you are concerned about performance.

    Your first idea about iterate over all the options and check the value property is better (speaking about performance) than traversing the DOM tree looking for an element with a particular value in one of their attributes (look at this comparison). You need to be aware that shorter code is not the same as faster code.

    A faster solution is to generate an array of strings at the beginning and search the correct value inside it in the validation process:

    //---At the beginning of your application
    let list = Array.prototype.map.call(document.getElementById("colours").options, (option) => option.value);
    
    //---Later in your validation process
    if (list.indexOf(value) < 0) {
        //Invalid
    }
    

    Another faster solution is to generate an object at the beginning and use it as a hash map, checking for the correct value inside it in the validation process:

    //---At the beginning of your application
    let hashmap = Array.prototype.reduce.call(document.getElementById("colours").options, (obj, option) => {
        if (!obj[option.value]) { obj[option.value] = true; }
        return obj;
    }, {});
    
    //---Later in your validation process
    if (!hashmap[value]) {
        //Invalid
    }
    

    Here you have the four methods compared in measurethat:

    1 - Your first idea (iterate over all the Datalist options)

    2 - Use the jQuery find method (@nsthethunderbolt solution)

    3 - Create an array of strings at the beginning and search the value in the Array in the validation process

    4 - Create a hash map at the beginning and check if the value is true in the validation process

    https://www.measurethat.net/Benchmarks/Show/4430/0/search-an-option-inside-a-datalist

提交回复
热议问题