revalidateField not working

3.7k views Asked by At

I'm using this plugin to validate my form.

On my form, I have a password input and a 'show password' checkbox. When the user clicks on show password, the input changes from password type to text.

$('#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');
});

so basically the input type changed (but keeps the same name) and I need to revalidate the field but it's not working.

2

There are 2 answers

0
Avinash On

One problem can be because of you are cloning all attributes of your password field even id too. And as per w3 standards you should not have two elements with the same ID attribute.

So you may try below code:

$('#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');
});
0
Arkni On

When working with complex form, the fields might be added to (or remove from) the form dynamically. The newly added fields also need to be validated.

So after removing your field and create a new one, you have to add it to formavalidation using the addField method.

See the following code:

$('#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');
});

Working example:

References: