2

我正在使用这个插件来验证我的表单。

在我的表单上,我有一个密码输入和一个“显示密码”复选框。当用户单击显示密码时,输入从密码类型更改为文本。

$('#show_password').off();
$('#show_password').on('click', function() {
  var change = '';
  var $input = $('#cpassword');
  if ($(this).is(':checked')) {
    change = 'text';
  } else {
    change = 'password';
  }
  var rep = $('<input type="' + change + '" />')
    .attr('id', $input.attr('id'))
    .attr('name', $input.attr('name'))
    .attr('class', $input.attr('class'))
    .val($input.val())
    .insertBefore($input);
  $input.remove();
  $input = rep;
  $('#frm_user_details').formValidation('revalidateField', 'password');
});

所以基本上输入类型发生了变化(但保持相同的名称),我需要重新验证该字段但它不起作用。

4

2 回答 2

1

一个问题可能是因为您也在克隆密码字段的所有属性id。根据 w3 标准,您不应该有两个具有相同 ID 属性的元素。

所以你可以试试下面的代码:

$('#show_password').off();
$('#show_password').on('click', function() {
  var change = '';
  var $input = $('#cpassword');
  if ($(this).is(':checked')) {
    change = 'text';
  } else {
    change = 'password';
  }
  var rep = $('<input type="' + change + '" />')
    .attr('id', $input.attr('id')+'_text')
    .attr('name', $input.attr('name'))
    .attr('class', $input.attr('class'))
    .val($input.val())
    .insertBefore($input);
  $input.remove();
  $input = rep;
  $('#frm_user_details').formValidation('revalidateField', 'password');
});
于 2015-06-16T18:22:55.813 回答
1

处理复杂表单时,可能会动态地将字段添加到表单中(或从表单中删除)。新添加的字段也需要验证。

因此,在删除您的字段并创建一个新字段后,您必须将其添加到formavalidation使用该addField方法。

请参阅以下代码:

$('#show_password').off();
$('#show_password').on('click', function () {
    var change = '';
    var $input = $('#cpassword');
    if ($(this).is(':checked')) {
        change = 'text';
    } else {
        change = 'password';
    }

    var rep = $('<input type="' + change + '" />')
        .attr('id', $input.attr('id'))
        .attr('name', $input.attr('name'))
        .attr('class', $input.attr('class'))
        .val($input.val())
        .insertBefore($input);

    $input.remove();
    $input = rep;

    // Add the new field to the plugin
    // For the second param, you can either use the field object or its name.
    // See
    //    http://formvalidation.io/api#add-field
    $('#frm_user_details').formValidation('addField', $input);

    // Finaly revalidate it
    $('#frm_user_details').formValidation('revalidateField', 'password');
});

工作示例:

参考:

于 2015-06-16T20:12:07.903 回答