2017-09-13 18 views
0

私には、2つの入力フィールド:携帯電話と電話があります。これらのフィールドの少なくとも1つが必要なので、フォームを提出することができます。携帯電話の番号を入力すると、電話入力が不要になります。必須=他の入力フィールドの条件付き入力フィールド

<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)ルールオブジェクトに妥当性検査ルールを入れる必要があります。

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

関連する問題