简体   繁体   中英

How to efficiently validate multiple input fields in a form

I have a form with three input fields, fname , lname , and age . I want to create a function in JavaScript that check's if all the fields have a value when it's submitted. To validate only one input field I have been using this:

function hasValue() {
    var value = document.forms["personalInfo"]["fname"].value;
    if (!value) {
        alert("The field needs a value!")
        return false;
    }
}

To validate multiple inputs I have been using this:

function hasValue() {
    var fnameVal = document.forms["personalInfo"]["fname"].value;
    var lnameVal = document.forms["personalInfo"]["lname"].value;
    var ageVal = document.forms["personalInfo"]["age"].value;
    if (!fnameVal || !lnameVal || !ageVal ) {
        alert("All fields needs a value!")
        return false;
    }
}

HTML:

<form name="personalInfo" onsubmit="return hasValue()">
    <input type="text" name="fname" placeholder="Jaun"><br>
    <input type="text" name="lname" placeholder="Deag"><br>
    <input type="number" name="age" placeholder="23"><br>
    <input type="submit" value="Register" name="registrer">
</form>

Is there a better/more efficient way to validate these inputs using a function in JavaScript?

The ideal solution here would be to set the required attribute on each input and let the browser handle the validation for you.

If you'd prefer a JS method instead, read on.


How about using some array manipulation like this:

function isFormIncomplete(formName, fieldNames) {
    const form = document.forms[formName];
    return fieldNames.some(field => !form[field].value);
}

isFormIncomplete(['fname', 'lname', 'age']);

This function starts with an array of field names ( ['fname', 'lname', 'age'] ) which is reduced using some() . This function returns true if the predicate function ( field => !form[field].value ) returns true for at least one element in the array. In this case, the predicate returns true if there is no value, so the result of some() is true if any field is empty.

That looks completely fine. Moreover, in live projects, readability and maintainability is more important then the efficiency of the js you have there. And actually less lines does not eve mean more/less efficiency.

What I normally do is to have different function for each input I'm validating. Then I call this validation function in blur or change events of each input. Then of course, another aggregated (with each validation function) function should be called on submit event of the form .

In your case since each field has the same strategy for validation, you can use another function to be called from input-specific validation function. This way you are not repeating any code, in other words you are reusing your validation function. At the same time, now it's much easier to add just another validation strategy to any input you have (isNumber, betweenRange, etc.).

Give id's to each element in your HTML, and target it like this:

function hasValue() {
     var fnameVal = document.getElementById('fnameVal').value
     if (!fnameVal) {
         alert("The field needs a value!")
     }
}

Or you can just add a "required" attribute in the input tag, although that only works with specific browsers like Chrome

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