Подтвердить что ты не робот

Использовать addMethod в jQuery Validate plugin

Я хочу проверить текстовое поле с помощью специального метода проверки jQuery Validate (addMethod), но мой код не работает. Может ли кто-нибудь помочь мне найти ошибку? Я никогда не пользовался специальным методом проверки, поэтому мне было трудно найти, где я ошибся в этом коде.

Это мой код:

$(document).ready(function () {

jQuery.validator.setDefaults({
  // where to display the error relative to the element
  errorPlacement: function(error, element) {
      error.appendTo(element.parent().find('div.myErrors'));
     }
 });

 jQuery.validator.addMethod(
"selectnic"
function(value,element){
if(element.value == /^[0-9]{9}[vVxX]$/)
   return false;
   else return true;
},
"wrong nic number"
); 



    $('#basicDetails').validate({ // initialize the Plugin
        rules: {
                fname: {
                    required: true,
                    lettersonly: true,
                },
                lname: {
                    required: true,
                    lettersonly: true,
                },  
            },
        messages: {
           fname: {
                required:"Please enter your first name",
                lettersonly: "Login format not valid",

            },
             lname: {
                required:"Please enter your last name",
                lettersonly: "Login format not valid",  
            },
        },
        submitHandler: function (form) { 
            alert('valid form submitted'); 
            return false; 
        }
    });

});

.. html code....

<form action="#" method="post"  id="basicDetails" runat="server">

 <table width="68%" border="0" cellpadding="6" cellspacing="6">


 <tr>
                                    <td>&nbsp;</td>
                                    <td> First name </td>
                                    <td>:</td>
                                    <td><input type="text" name="fname" id="fname" class="textbox" placeholder="Required field"/><div class="myErrors"></div></td> &nbsp;
                                    <td align="right"> Last name&nbsp; :</td>
                                    <td><input type="text" name="lname" class="textbox" id="lname" placeholder="Required field"/><div class="myErrors"></div></td>
                                </tr>

                                <tr>
                                    <td>&nbsp;</td>
                                    <td width="147" > NIC no </td>
                                    <td> : </td>
                                    <td width="172"><input type="text" name="nic" id="nic"   class="textbox"  placeholder="Required field"/><div class="myErrors"></div></td>
                                    <td width="167" align="right">Passport no &nbsp; :</td>
                                    <td width="167" id="showPP"> <input type="text" name="passport" class="textbox" id="ppnu" placeholder="Required field"/></td>    
                                </tr>
                                <tr>
                                    <td>&nbsp;</td>
                                    <td>&nbsp;</td>
                                    <td colspan="3"><input type="submit" name="submit"  value="Submit "class="submit"   id="submit" />&nbsp; &nbsp;
                                    <input type="submit" name="reset"  value="Reset "class="reset" />
                                    </td>                                
                                </tr>


 </table>





</form>

..... после редактирования моего кода....

$(document).ready(function () {



jQuery.validator.setDefaults({
  // where to display the error relative to the element
  errorPlacement: function(error, element) {
      error.appendTo(element.parent().find('div.myErrors'));
     }
 });

 jQuery.validator.addMethod("selectnic", function(value, element){
    if (/^[0-9]{9}[vVxX]$/.test(value)) {
        return false;
    } else {
        return true;
    };
}, "wrong nic number"); 


    $('#basicDetails').validate({ // initialize the Plugin


        rules: {
                fname: {
                    required: true,
                    lettersonly: true,
                        },
                lname: {
                    required: true,
                    lettersonly: true,
                    },

                 nicnumber: {
                            // other rules,
                        selectnic: true // <-  declare the rule someplace!
                            }


            },


        messages: {

           fname: {
                required:"Please enter your first name",
                lettersonly: "Login format not valid",

            },
             lname: {
                required:"Please enter your last name",
                lettersonly: "Login format not valid",

            },
        },


        submitHandler: function (form) { // for demo
            alert('valid form submitted'); // for demo
            return false; // for demo
        }
    });

});
4b9b3361

Ответ 1

Существуют три различные проблемы, описанные в последующих изменениях ниже.


1) Вы пропустили запятую только между selectnic и function(.

Кроме того, попробуйте использовать этот формат при использовании regex...

jQuery.validator.addMethod("selectnic", function(value, element){
    if (/^[0-9]{9}[vVxX]$/.test(value)) {
        return false;  // FAIL validation when REGEX matches
    } else {
        return true;   // PASS validation otherwise
    };
}, "wrong nic number"); 

EDIT. Этот ответ предполагает, что ваш оригинальный regex и логика верны. Ваша логика возвращает false, когда regex является совпадением. false означает, что проверка не выполнена, и вы увидите сообщение об ошибке.


2) EDIT 2:

После создания новых методов вы также должны их использовать. Я не вижу, чтобы правило/метод selectnic использовали любое место в вашем коде.

Пример:

rules: {
    myFieldName: {
        // other rules,
        selectnic: true // <-  declare the rule someplace!
    }
}

3) ИЗМЕНИТЬ 3:

И, наконец, логика OP оригинала true/false была обратной. Он хотел выполнить проверку PASS при регулярном совпадении... поэтому необходимо return true.

    if (/^[0-9]{9}[vVxX]$/.test(value)) {
        return true;   // PASS validation when REGEX matches
    } else {
        return false;  // FAIL validation
    };

ДЕМО: http://jsfiddle.net/DzvNr/