1

I am using parsley.js and I have to dynamically show/hide validation according to the data the user has selected.

I have read this SO post to dynamically add or remove required fields to be validated by parsley, which was helpful.

But how do I dynamically remove and add the maxlength for an input field?

I have tried the following two options:

$('input').attr('data-parsley-maxlength', 'true');
$('input').attr('data-parsley-maxlength', true);

But the above gives the following error message:

This value is too long. It should have true characters or fewer.
Community
  • 1
  • 1
user1261774
  • 3,525
  • 10
  • 55
  • 103

1 Answers1

3

I reckon you just need to assign correct value type to the attribute, data-parsley-maxlength which is numerical value, see here: http://parsleyjs.org/doc/#validators-overview

Maxlength #2.0 --> data-parsley-maxlength="10" --> Validates that the length of a string is not larger than the given limit.

Hope this will fit your need :)

Try this:

//destroy parsley
$('form').parsley().destroy();

//set required attribute on input to value type
$('input').attr('data-parsley-maxlength', '0');

//reinitialize parsley
$('form').parsley();
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
  • Thanks for the post, But, what is the difference in using the # as follows: `$('input').attr('data-parsley-maxlength', '0');` compared to `$('#input').attr('data-parsley-maxlength', '0');` Should I be using the # symbol in the parsley code? I think this is where my problem is, but cannot quite figure it out with my code, so I have to ask a really basic question. – user1261774 Aug 24 '14 at 09:33
  • 2
    @user1261774 glad it helped; The hash (#) specifies to select elements by their ID's, read here ==> http://stackoverflow.com/questions/2860394/what-do-dot-and-hash-symbols-mean-in-jquery and jquery documentation -> http://api.jquery.com/category/selectors/basic-css-selectors/ . The `$('input')` means validation on any `` html element. – Tats_innit Aug 24 '14 at 09:55
  • @Tats_innit Is reinitializing also necessary when changing the value of an existing `data-parsley-maxlength`?` – awendt Mar 02 '17 at 09:16
  • 1
    Hiya @awendt I had a quick peek inside parsley, seems like yes at this stage. :) correct me if I am wrong. – Tats_innit Mar 09 '17 at 02:15