jQuery: how to validate an input text before submit or change the cursor?

Hi,

using jQuery, how to validate a required input text before submitting or placing the cursor in another field?

I’ve tried this below but it doesn’t work.

$(document).ready(function() {
  $("#form").validate({
    rules: {
      name: "coche4[marca]",
      required: true
      }
    },
    messages: {
      comment: "You must insert something."
    }
  });
});

Regards

The standard jQuery validation doesn’t have binded methods by default, try the below code and simply replace #field-id with the ID of your input field

$(document).ready(function() {
    $('#field-id').bind('keyup', function(){
        alert($(this).val());
    });
});

I don’t think the above advice will be of much help here.

The issue with the original code is that the keys inside the rule are supposed to be the name attributes of the form fields.
So you would need to use:


rules: {
    'coche4[marca]': {
        required: true
    }
},

Or you could simplify it to:


rules: {
    'coche4[marca]': 'required'
},

There’s more sample code for the rules over at the validate documentation page, such as:


$(".selector").validate({
   rules: {
     contact: {
       required: true,
       email: {
         depends: function(element) {
           return $("#contactform_email:checked")
         }
       }
     }
   }
});

Oh yes, the same applies for the messages part too. The validator does have its own default messages, but you can customise it for the field with:


messages: {
  'coche4[marca]': "You must insert something."
}

There’s more sample code for the messages over at the validate documentation page, such as:


$(".selector").validate({
   rules: {
     name: "required",
     email: {
       required: true,
       email: true
     }
   },
   messages: {
     name: "Please specify your name",
     email: {
       required: "We need your email address to contact you",
       email: "Your email address must be in the format of [email]name@domain.com[/email]"
     }
   }
});