JQuery validates custom rule in data attributes

I have input that already has some validation rules

<input type="text" value="" placeholder="Write the code here" 
       name="myCode" id="myCode" data-rule-required="true" 
       data-msg-required="Required field" class="form-control" 
       aria-required="true">

and created your own rule to check the syntax of the code

$("#myCode").rules("add", { checkCode: 
    function () { 
        return $('input[name=codeText]').val(); 
    } 
});

Using this method, I determine what myCodeshould be checked using the method checkCode, which in turn takes a value into the input codeText.

It works very well. However, to maintain clean code, I would like to move the rule definition inside the attribute data-*, but I cannot figure out how to write code to dynamically pass the return equivalent $('input[name=codeText]').val(). Please see the question marks below.

<input type="text" value="" placeholder="Write the code here" 
       name="myCode" id="myCode" 
       data-rule-required="true" data-msg-required="Required field" 
       data-rule-checkCode="????" data-msg-checkCode="Invalid code" 
       class="form-control" aria-required="true">

What do I need to add to the attribute value ???

EDIT

Sparky answer . :

<input type="text" value="" placeholder="Write the code here" 
   [...]
   data-rule-checkCode="input[name=codeText]" 
   [...]>

$.validator.addMethod("checkCode", function(value, element, param) {
    return $(param).val();
}, '...');
+4
1

$("#myCode").rules("add", { checkCode: 
    function () { 
        return $('input[name=codeText]').val(); 
    } 
});

.rules() , . , .

. .addMethod() - .

jQuery.validator.addMethod("checkCode", function(value, element) {
    return $('input[name=codeText]').val();
}, 'Please enter a valid email address.');

.rules('add'), ...

$('input[name="myCode"]').rules('add', {
    checkCode: true
});

.: http://jqueryvalidation.org/jQuery.validator.addMethod/


, name ...

jQuery.validator.addMethod("checkCode", function(value, element, param) {
    return $('input[name=' + param + ']').val();
}, 'Please enter a valid email address.');

...

$('input[name="myCode"]').rules('add', {
    checkCode: "codeText"
});

, , , .rules().

, checkCode data-rule-checkCode="true" data-rule-checkCode="codeText".

+3

Source: https://habr.com/ru/post/1611103/


All Articles