0

I am using jQuery validate plugin to validate the form data at the input point. For most of the pages, the validation is standards where I accept any non-empty value. However, there are forms in some pages which require specific validation (e.g. a pattern match)

I have included the generic validation function in the templates and the validation happens as expected. But I am finding it difficult to figure out how to extend the above functions only for specific pages by adding an additional lines of code, giving the main function the capability to perform page-specific validations. I have checked 1, 2 3 and many other answers and had no luck. I do not need to replace the entire validation function, but to add specific parameters based on page.

This question was not helpful since I am calling onclick function and NOT a simple function. What am I missing?

My main validation function is below

jQuery(document).ready(function() {
    if(jQuery().validate) {
        jQuery('#maindataform').validate({
            ignore: ":hidden:not(select)",
            errorClass: "is-invalid",
            validClass: "is-valid",
            errorPlacement: function(error, element) {
                error.insertAfter(element);
            },
            //add rules parameters here
            //add message parameters here
        });

        jQuery('#maindataformbtn').click(function() {
            var formstatus = jQuery('#maindataform').valid();
            if (formstatus) {
                //alert ("valid");
                jQuery('#maindataform').submit();
            }
        });
    }
});

Page-specific parameters I am trying to add

    rules: {
        nic: {
            pattern: "^[0-9]{9}(V|X)$)|(^[0-9]{12}$"
        },
    },
    messages: {
        nic: {
            pattern: "NIC can have 9 numbers with 'V' or 12 numbers only"
        },
    }
Sparky
  • 98,165
  • 25
  • 199
  • 285
Sid
  • 1,255
  • 2
  • 22
  • 45
  • See item 1b in this answer: https://stackoverflow.com/a/9056425/594235 – Sparky Jan 22 '21 at 20:00
  • 1
    You could also use the `.rules()` method to dynamically add the rules on the specific page. – Sparky Jan 22 '21 at 20:01
  • @Sparky Thank you. `.rules()` in *2b* worked well even though 1b did not. Is there any method to display messages such as `.messages()`? (I tried messages() but didn't work) – Sid Jan 24 '21 at 05:41
  • 1
    `messages` is a parameter you can use inside of the `.rules()` option. Please refer to the documentation. http://jqueryvalidation.org/rules – Sparky Jan 25 '21 at 18:30
  • @Sparky Oh sorry I missed that. Thank you! – Sid Jan 28 '21 at 04:44

0 Answers0