javascriptjqueryfunctionvalidationspry

jQuery Validate() special function


I'm using the jQuery validate() plugin for some forms and it goes great. The only thing is that I have an input field that requires a special validation process. Here is how it goes:

The jQuery validate plugin is called in the domready for all the required fields.

Here is an example for an input:

<li>
    <label for="nome">Nome completo*</label>
    <input name="nome" type="text" id="nome" class="required"/>
</li>

And here is how I call my special function:

<li>
    <span id="sprytextfield1">
        <label for="cpf">CPF* (xxxxxxxxxxx)</label>
        <input name="cpf" type="text"  id="cpf" maxlength="15" class="required" />
        <span class="textfieldInvalidFormatMsg">CPF Inv&aacute;lido.</span>
    </span>
</li>

And at the bottom of the file I call the Spry function:

<script type="text/javascript">
    <!--
        var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1","cpf");
    //-->
</script>

Of course I call the Spry CSS and JavaScript files in the head section as well as my special-validate.js.

When I just use the jQuery validate() plugin and click on the send button, the page goes automatically back to the first mistaken input field and shows the error type (not a number, not a valid email etc.).

But with this new function, this "going-back-to-the-first-mistake" feature doesn't work, of course, because the validate() function sees it all good.

I already added a rule for another form (about pictures upload) and it goes like this:

$("#commentForm").validate({
    rules: {
        foto34: {
            required: true,
            accept: "jpg|png|gif"
        }
    }
});

Now my question is, how can I add the special validation function as a rule of the whole validation process?

Here is the page to understand it better: link text and the special field is the first one: CPF.

I hope I was clear explaining my problem.


Solution

  • I'll answer my own question as I just found the solution. I added the JavaScript function to check my cpf number (Brazilian ID number) just before the DOM ready opening like this:

    jQuery.validator.addMethod(
        "cpf",
        function (valor){
            ...
        },
        "CPF inv&aacute;lido"
    );
    

    and then here goes my DOM ready:

    $(document).ready(function(){
        $("#commentForm").validate({
            rules: {
                campocpf: {
                    required:true,
                    cpf:true
                },
            }
        });
    });
    

    If it does interest some Brazilians, I can show the whole function that does the CPF validation (checked with my own number, works). I also have another one for the CNPJ number (Brazilian number for companies).