How to apply jQuery Validate rules to multiple fields at once?

Asked

Viewed 624 times

1

I have an ASP.NET form and am using jQuery Validate to apply validation rules in the fields. All my fields have a common rule (required: true) but I couldn’t find a way to apply it all at once.

$('#form1').validate({
        rules: {
            '<%= txtRazaoSocial.UniqueID %>': {
                required: true
            },
            '<%= txtNomeFantasia.UniqueID %>': {
                required: true
            },
            '<%= txtCNPJ.UniqueID %>': {
                required: true,
                cnpj: true
            },
            '<%= txtCEP.UniqueID %>': {
                required: true
            },
            '<%= txtLogradouro.UniqueID %>': {
                required: true
            },
            '<%= txtNumeroLogradouro.UniqueID %>': {
                required: true
            },
            '<%= txtBairro.UniqueID %>': {
                required: true 
[...]

This problem can be solved?

EDIT: I tried the way below too, but it didn’t work.

$('#form1').validate({
    rules: {
      required: true,
    },
  • 1

    Add the required class to all Fields

2 answers

1


You can also try this

//Você coloca todos os campos que tiver, select, textarea etc..
$("#form1 input").each(function () {
  $(this).rules("add", {
    required: true
  });
});

Or add class="required" in the fields of your form, as stated in the comments.

  • 1

    I considered this as the correct answer because one of the proposed solutions was only to add the 'required' class in the fields, which solved my problem. Anyway, thank you all!

0

Add

class="required"

In the fields you want to become mandatory.

And in javascript do

$(function () {
  $.validator.setValidator('idDoSeuForm');
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.