2

I'm building a plugin to manage course information and am struggling to put form validation on the new meta boxes I've added.

Has anyone a good way of putting JS / JQuery validation on the admin menus?

Thanks

  • Instead of just asking for us to do it for you, please post the code you've already attempted to work with. – EAMann Jul 12 '12 at 18:04
  • Well I had a lot of goes at it so there was a lot of different code. I was more wondering if anyone had made it work rather than just do it for me. I should have been a bit clearer about that in the question. – danbrown Jul 19 '12 at 7:55
4

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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.