简体   繁体   中英

Make Form Fields Optional with JavaScript Validation

I have JavaScript form validation functions like so:

function validate_name(field) 
{
    if (field == "") return "Please enter the name.\n";
    return "";
}

function validate_specialty(field) 
{
    if (field == "") return "Please enter the specialty.\n";
    return "";
}

function validate_location(field) 
{
    if (field == "") return "Don't forget the location.\n";
    return "";
}

where the function that is called from the form's onSubmit is:

function validate_fields(form)
{
    fail  = validate_name(form.name.value);
    fail += validate_specialty(form.specialty.value);
    fail += validate_location(form.location.value);

    if (fail == "")     
        return true;
    else 
    { 
        alert(fail); 
        return false;
    }
}

This works fine but I have decided that I don't want all three to necessarily be required. It would be great if I could make these three optional, such that if any one of these fields is filled in, it would validate true, but if all three fields are empty, I could throw an alert and validate false.

Any help is much appreciated.

You can do that by capturing the results separately, and testing with an OR grouping.

function validate_fields(form)
{
    fail1 = validate_name(form.name.value);
    fail2 = validate_specialty(form.specialty.value);
    fail3 = validate_location(form.location.value);

    if (fail1 == "" || fail2 == "" || fail3 == "")     
        return true;
    else 
    { 
        alert(fail1 + fail2 + fail3); 
        return false;
    }
}

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