简体   繁体   English

验证是否填写了两个表单字段之一?

[英]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. 至少需要两个字段之一,如果发送了表单,则填写了字段1或填写了字段2,则仅填写了其中之一。 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). 我正在尝试使用下面的代码执行此操作,但工作不正常,它只能像要求的字段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. 这是一个简单的情况,在每个长度上使用非运算符进行AND条件。

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

So it's saying if field1 is empty AND field2 is empty then the form is invalid. 这就是说,如果field1为空,而field2为空,则该表单无效。

This assumes field1 and field2 are the string value and not the DOM elements. 假定field1field2是字符串值,而不是DOM元素。 If they're DOM elements then you need to use field1.value.length and field2.value.length . 如果它们是DOM元素,则需要使用field1.value.lengthfield2.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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM