JS / JQuery form validation in backend admin menus

Ok got it to work. I couldn’t find anything on the web about this, bar one guy’s page, which did actually work but wasn’t quite as good a solution as I’d wanted. I did some research how the main plugins are doing it, and only found some unintuitive custom JS ways.

Anyway success I got it to work using a JQuery library in the end. I put the scripts in the footer because I needed to target a specific page:

add_action('admin_footer', 'cpd_validator', 999);

function cpd_validator(){

    global $post;
    if($post->post_type == 'courses' || $post->post_type == 'presentations'){

        // page specific validation here...
        wp_enqueue_script('form_validation', plugins_url('form-validation/jquery.validate.min.js', __FILE__));
        wp_enqueue_script('calibrate', plugins_url('form-validation/calibrate.js', __FILE__));
    }
}

The jquery.validate.min.js is here. The calibrate script looks something like:

jQuery(function(){

    // Initialise the validator
jQuery('#post').validate();

    // Add the rules to the classname hooks
jQuery.validator.addClassRules({
    max_100: {
         maxlength: 100
    },
    max_4000: {
        maxlength: 4000
    },
    number: {
        number: true
    }

});

And then I added the classes I’d defined to the actual form elements in the meta-boxes:

<label for="subject">Subject: </label>
<input type="text" class="max_100" value="<?php echo $subject; ?>" name="subject" id="subject" >

And that worked 🙂