CLL CLL - 7 months ago 163
Javascript Question

How can I add a check if a signature is entered using jquery validation and signature_pad?

I'm using jquery.validate.js to validate multiple fields in my form along with smizek's signature_pad. I want to validate if something is drawn on the html canvas (signature pad) at the same time all the other input fields are validated.

Unfortunately, adding a function to the jquery validation submithandler to check if the canvas has a signature is not sufficient because this only triggers once all other required fields are satisfied. I can add methods to jquery validator, but I'm pretty sure those only work on validating the content of inputs—not a canvas.

I can check if the signature exists with "signaturePad.isEmpty()". Ideally, there would be a way to add a function like this that happens concurrently with any validation:

var errorExists = false;
if( signaturePad.isEmpty()){
if (errorExists == false){
$( "#signature-pad" ).append( "<div id="sig-error">A signature is required</div>" );
errorExists = true;
}
}else if( !signaturePad.isEmpty()) {
if (errorExists == true){
$('#sig-error').remove();
}
}


...and only continue on to actually submit the form if both the jquery validation and the signature are satisfied.

Is there a way to have a function trigger at the same time other validation happens—not after? How can I stop the form from submitting unless both my conditions are met—not just the jquery validation?

CLL CLL
Answer

In the jquery validation submithandler, return false if the signature is not filled:

    if( signaturePad.isEmpty()){
            console.log('it is empty');
            return false;            
        }

This prevents the form from being submit if there is no signature.

To show an error message for a missing signature like the rest of the jquery validation error messages, bind a function to the submit input's click:

    $('#submit_form').click(function(){
      if( signaturePad.isEmpty()){
        if (errorExists === false){
          $( "#signature-pad" ).append( "<div class='error' id='sig-error'>A signature is required</div>" );
          errorExists = true;
        }
      }else if( !signaturePad.isEmpty()) {
        if (errorExists === true){
          $('#sig-error').remove();
          errorExists = false;
        }
      }
    });

Declare your variable somewhere: var errorExists = false;