2017-09-13 114 views
0

我有一個從2輸入字段:手機和電話。我希望這些字段中至少有一個是必需的,這樣表單才能被引用。您可以輸入手機號碼,不再需要電話輸入或以其他方式輸入。必需=「必需」輸入字段有條件的另一個輸入字段

<input class="form-control telephone" type="text" placeholder="Telephone" required="required" maxlength="100" pattern="^\+?[0-9 /-]*$"/> 

<input class="form-control cellphone" type="text" placeholder="Cellphone" required="required" maxlength="100" pattern="^\+?[0-9 /-]*$"/> 

我發現Jquery驗證器有條件聲明,但我不知道如何使用它們或他們沒有在我的代碼中工作。繼承人我有什麼

$("#myForm").validate({ 
firstInput: { 
    required: function(element){ 
     return $(".cellphone").val().length > 0; 
    } 
}, 
secondInput: { 
    required: function(element){ 
     return $(".telephone").val().length > 0; 
    } 
} 
}); 
+0

你可以做到這一點,即使沒有使用jQuery validator.You只需要訪問這兩個字段的值,並檢查是否都沒有empty.Then如果兩個都是空的,那麼你只阻止提交併顯示錯誤 – Debabrata

回答

2

1)您需要將驗證規則放在rules對象中。

2)你的if語句是錯誤的。如果另一個輸入爲空(otherInput.val().length == 0),則需要輸入(required: true)。

3)您需要爲輸入指定名稱屬性。

$("#myForm").validate({ 
 
    rules: { 
 
    firstInput: { 
 
     required: function(element){ 
 
      return $(".cellphone").val().length == 0; 
 
     } 
 
    }, 
 
    secondInput: { 
 
     required: function(element){ 
 
      return $(".telephone").val().length == 0; 
 
     } 
 
    } 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script> 
 
<form id='myForm'> 
 
    <input class="form-control telephone" type="text" placeholder="Telephone" maxlength="100" name="firstInput" pattern="^\+?[0-9 /-]*$"/> 
 
    <input class="form-control cellphone" type="text" placeholder="Cellphone" name="secondInput" maxlength="100" pattern="^\+?[0-9 /-]*$"/> 
 
    <input type="submit"> 
 
</form>

+0

完美!謝謝! – pepote

相關問題