Skip to content Skip to sidebar Skip to footer

Custom Validation For JQuery Validate (two Method In One)

I would like to know, how can I call another custom validation method of jquery validate in my method to validate some data. For sample, I have a field called 'Document ID' that ca

Solution 1:

What about this?

jQuery.validator.addMethod("documentoId", function(value, element) {

   if (value.length <= 11) {
      jQuery.validator.methods.cpf.call(this, value, element);
   }
   else if (value.length <= 14) {
      jQuery.validator.methods.cnpj.call(this, value, element);
   }

}, 'Documento inválido');

Full example changing the error message

jQuery.validator.addMethod("documento", function(value, element) {

  // remove pontuações
  value = value.replace('.','');
  value = value.replace('.','');
  value = value.replace('-','');
  value = value.replace('/','');

  if (value.length <= 11) {
    if(jQuery.validator.methods.cpf.call(this, value, element)){
      return true;
    } else {
      this.settings.messages.documento.documento = "Informe um CPF válido.";
    }

  }
  else if (value.length <= 14) {
    if(jQuery.validator.methods.cnpj.call(this, value, element)){
      return true;
    } else {
      this.settings.messages.documento.documento = "Informe um CNPJ válido.";
    }

  }

  return false;

}, "Informe um documento válido.");

Solution 2:

jQuery.validator.addMethod("cnpj", function(value, element) {
    return this.optional(element) || /^[0-9]{2}.[0-9]{3}.[0-9]{3}?\/[0-9]{4}-[0-9]{2}$/.test(value);
}, "Formato: 00.000.000/0000-00");

Solution 3:

how about creating those function outside of the scope of the validation definition (i.e not using anonymous functions)?

function cpfValide(value,element) {
  //something
}

function cnpjValide(value,element){
  //something
}
jQuery.validator.addMethod("cpf", cpfValide, "CPF inválido!");


jQuery.validator.addMethod("documentoId", function(value, element) {
  return cpfValidate(value,element) || cnpjValidate(value,element);
//..
}

Post a Comment for "Custom Validation For JQuery Validate (two Method In One)"