Jquery.Validate - 基于哪个选项卡添加/删除规则 [英] Jquery.Validate - Add / Remove Rules based on which tab

查看:28
本文介绍了Jquery.Validate - 基于哪个选项卡添加/删除规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Bootstrap 4 选项卡式界面,每个选项卡上都有输入框.我希望允许用户根据他们所在的选项卡输入不同的必填字段,因此我希望基于该选项卡添加或删除验证.还有一些输入是强制性的,无论用户在哪个选项卡中.

I have a Bootstrap 4 tabbed interface with input boxes on each tab. I want to allow the user to input different Required fields based on which tab they are on, therefore I wish to add or remove validation based on that tab. There are also a few input that are mandatory, no mater what tab the user is in.

我所做的是创建一个默认验证函数,该函数添加了 2 个共享输入及其规则.然后,我使用 Bootstrap 事件来捕获单击了哪个选项卡,删除了任何现有验证并为该特定选项卡创建验证.

What I have done is create a Default Validation function that adds the 2 shared inputs and their rules. I then us the Bootstrap events to capture which tab is clicked, removed any existing validation and create validation for that specific tab.

我已经完成了 90% 的工作,但我最近注意到标签内的输入在来回切换时实际上并没有被重置.我曾尝试使用 addmethod,但根本没有让新规则发挥作用.

I have 90% of this working, though I've recently noticed that the inputs inside the tab do not actually get reset when tabbing back and forth. I have attempted to use addmethod but simply never got the new rules to function.

我的现实生活应用程序有超过 2 个标签,所以我也不能简单地在 2 组规则之间来回切换.

My Real life app has more than 2 Tabs so i also cannot simply toggle back and forth between on 2 sets of rules.

提琴手这里

var currTab = '#tab1';
ValidationDefaults();
Tab1Validation();


$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
  currTab = $(e.target).attr("href"); // activated tab

  ClearValidation();
  ValidationDefaults();

});

$('#btnSubmit').on('click', function(e) {

  switch (currTab) {
    case "#tab1":

      Tab1Validation();
      break;
    case "#tab2":

      Tab2Validation();
      break;
  }

  if ($("form").valid()) {

  }
});


function Tab1Validation() {

  //https://stackoverflow.com/a/28954059/1555453
  var validator = $("#Create").validate({
    rules: {
      username: {
        require_from_group: [1, ".Tab1Group"]
      },
      username2: {
        require_from_group: [1, ".Tab1Group"]
      }
    },
    messages: {
      username: "* You must enter either a username or a Username 2",
      username2: "* You must enter either a username or a Username 2"
    }
  });

}

function Tab2Validation() {

  //https://stackoverflow.com/a/28954059/1555453
  var validator = $("#Create").validate({
    rules: {
      street: {
        required: true
      },
      city: {
        required: true
      }
    },
    messages: {
      street: "* You must enter either a street",
      city: "* You must enter either a city"
    }
  });

}

function ClearValidation() {
  var validator = $("#Create").validate();
  validator.resetForm();

  $('#Create').removeData('validator');
  ValidationDefaults();
}

function ValidationDefaults() {

  $.validator.setDefaults({
    rules: {
      firstname: {
        required: true
      },
      lastname: {
        required: true
      }
    },
    messages: {
      firstname: "* A first name is Required",
      lastname: "* A last name is Required"
    },
    errorElement: 'span',
    errorPlacement: function(error, element) {
      error.addClass('invalid-feedback');
      element.closest('.form-group').append(error);
    },
    highlight: function(element, errorClass, validClass) {
      $(element).addClass('is-invalid');
    },
    unhighlight: function(element, errorClass, validClass) {
      $(element).removeClass('is-invalid');
    }
  });
}

推荐答案

您的尝试是错误的方法...

Your attempt is the wrong approach...

.validate() 方法只能被调用一次来初始化表单上的插件,并且因为所有后续调用都将被调用被忽略,不能多次调用它来重写你的规则.

The .validate() method can only be called once for initializing the plugin on your form, and since all subsequent calls would be ignored, it cannot be called multiple times to re-write your rules.

处理所有这些的正确方法是:

The proper way to handle all of this would be to:

  1. 在页面加载时调用 .validate() 一次,然后
  2. 调用 .rules('add').rules('remove') 方法以根据需要动态切换规则.
  1. Call .validate() once on page load and then
  2. call the .rules('add') and .rules('remove') methods to dynamically toggle your rules as needed.

试试这样的:jsfiddle DEMO

var currTab = '#tab1'
ValidationDefaults();  // INITIALIZE PLUGIN ON FORM
Tab1Validation();      // SETUP TAB 1 with RULES

$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    currTab = $(e.target).attr("href"); // activated tab
});

$('#btnSubmit').on('click', function(e) {
    switch (currTab) {
        case "#tab1":
            Tab1Validation();
            break;
        case "#tab2":
            Tab2Validation();
            break;
    }
    if ($("form").valid()) {

    }
});

function Tab1Validation() {
    // ADD RULES FOR TAB 1
    $('#tab1 input').each(function() {
        $(this).rules('add', {
            require_from_group: [1, ".Tab1Group"],
            messages: {
                require_from_group: "* You must enter either username or username2"
            }
        });
    });
    // REMOVE RULES FOR TAB 2
    $('#tab2 input').each(function() {
        $(this).rules('remove');
    });
}

function Tab2Validation() {
    // ADD RULES FOR TAB 2
    $('#tab2 input').each(function() {
        $(this).rules('add', {
            required: true,
        });
    });
    // REMOVE RULES FOR TAB 1
    $('#tab1 input').each(function() {
        $(this).rules('remove');
    });
}

function ValidationDefaults() {
    // INITIALIZE PLUGIN ON PAGE LOAD
    $('#Create').validate({
        rules: {
            firstname: {
                required: true
            },
            lastname: {
                required: true
            }
        },
        messages: {
            firstname: "* A first name is Required",
            lastname: "* A last name is Required"
        },
        // combine messages into one for "require_from_group"
        groups: {  
            tab1: "username username2"
        },
        errorElement: 'span',
        errorPlacement: function(error, element) {
            error.addClass('invalid-feedback');
            element.closest('.form-group').append(error);
        },
        highlight: function(element, errorClass, validClass) {
            $(element).addClass('is-invalid');
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).removeClass('is-invalid');
        }
    });
}

请注意,我使用了 jQuery .each() 将所有规则一次应用于选项卡中的所有字段.如果您需要将唯一的规则/消息应用于单个字段,则删除 .each() 并根据需要将 .rules() 附加到单个字段选择器.

Note that I used a jQuery .each() to apply all the rules at once to all the fields within a tab. If you need to apply unique rules/messages to the individual fields then remove the .each() and attach .rules() to single field selectors as needed.

这篇关于Jquery.Validate - 基于哪个选项卡添加/删除规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆