2011-11-11 6 views
3

2つの入力フィールドを比較し、2つ目の入力フィールドが最初のフィールドよりも大きいかどうかを確認します。jQuery Validatorを使用して2つのフィールドを比較する方法

カスタムメソッドを追加する必要がありますか、またはメソッドの範囲で変数名を使用できますか?もしそうなら、構文を教えてくれますか?カスタムメソッドを持つ

var validateSection = function (theForm) { 
$(theForm).validate({ 
    rules: { 
     startPoint: { 
      required: true, 
      range: [0, 100] 
     }, 
     endPoint: { 
      required: true, 
      range: [startPoint + 1, 100] //Is this possible if I set the function to run on any change to either field? 
     }, 
} 
}); 

if ($(theForm).valid()) { 
    return true; 
} 
else { 
    return false; 
} 
} 

コード:私は形成するために取得する前に、$ .validatorを取得

$.validator.addMethod("endGreaterThanBegin", function(value, element) { 
    return endPoint > startPoint 
}, "* End Point Should be Greater than Start"); 

var validateSection = function (theForm) { 
    $(theForm).validate({ 
     rules: { 
      startPoint: { 
       required: true, 
       range: [0, 100] 
      }, 
      endPoint: { 
       required: true, 
       range: [1, 100], 
       endGreaterThanBegin: true 
      }, 
     } 
    }); 
    if ($(theForm).valid()) { 
     return true; 
    } 
    else { 
     return false; 
    } 
} 

が定義されていない、と私は入力フィールドにへ

+0

コードは私が$ .validatorが定義されていない取得、これを追加するときに何らかの理由でカスタムメソッドを提案 – jimdrang

答えて

11

必要性のテストを開始するとき、その後validateSectionは関数ではありません

から custom validate method

Protoypeを追加

検証 -

endate_greater_startdate : true 

Demoためのチェック、などの様々な例が、デバッグに役立ちます。

+0

をしようとして、コメントを追加し、私が取得するときそのページに私はvalidateSectionを取得するこれらのフィールドを混乱を開始する関数ではありません。私はちょうどそれが行く必要がある特別な場所はvalidateSection関数の上に追加しました? – jimdrang

+0

デモリンクを追加しました。 addmethodの例 – Jayendra

+0

デモが動作していません! –

0

Javascriptを

$(function() { 
    $.validator.addMethod('smaller_than', function (value, element, param) { 
     return +$(element).val() < +$(param).val(); 
    }); 
    $.validator.addMethod('not_smaller_than', function (value, element, param) { 
     return +$(element).val() > +$(param).val(); 
    }); 
    $('form').validate(); 
}); 

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script> 
<form> 
    value 1 
    <input name="value1" 
      data-rule-smaller_than="[name='value2']" 
      data-msg-smaller_than="value 1 must be smaller than value 2" /><br/> 
    value 2 
    <input name="value2" 
      data-rule-not_smaller_than="[name='value1']" 
      data-msg-not_smaller_than="value 1 must be smaller than value 2"/><br/> 
    <input type="submit"/> 
</form> 

JSFiddle

+0

良いアイデア。メッセージを追加する場所があれば良いでしょう –

関連する問題