简体   繁体   中英

Validate if one of two form fields is filled?

At least one of the two fields is required, if field 1 is filled or field 2 is filled the form is sent, the required is just one of them filled. I'm trying to do this with the code below, but isn't working fine, this is working only validating like required the field 1 (text1). Thank you!

 var field1 = text1; var field2 = text2; if (text2.length) { if (!field1.length || !field2.length) { return false; } } else if (!field1.length) { return false; } 
 <input type="text" placeholder="text 1*" name="text1" class="text1" data-target="previewText1" maxlength="11"> <input type="text" placeholder="text 2" value="" name="text2" class="text2" data-target="previewText2" maxlength="11"> 

It's a simple case of an AND condition on each length with the not operator.

if (!field1.length && !field2.length) {
    return false;
}

So it's saying if field1 is empty AND field2 is empty then the form is invalid.

This assumes field1 and field2 are the string value and not the DOM elements. If they're DOM elements then you need to use field1.value.length and field2.value.length .

Like that :

var field1 = document.getElementsByClassName("text1").value;
var field2 = document.getElementsByClassName("text2").value;

// Check if one of the fields is not empty
if (field1.length || field2.length) {
        return true;
}
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