3

Is there any way to get a reference of the input field and append it's value or label to the error message?

By default, the error messages are like "This value is required".

I want to change "This value" with the input label so that I get a better error message.

$( '#form' ).parsley({
    messages: {
        required: 'LABEL VALUE HERE + Error message'
    } 
});

Here is a a boilerplate to get you started: http://jsfiddle.net/82utb/

Adrian Florescu
  • 4,454
  • 8
  • 50
  • 74

2 Answers2

1

You could destroy parsley and re-init with new error message each time the label or value changes.

http://jsfiddle.net/doodlebot/yhcY6/

Here's the JS:

function updateMessage($target) {
    var inputValue = $target.val();
    var id = $target.attr('id');
    var valueOrLabel = inputValue ? inputValue : id;

    $('#form').parsley('destroy');
    $('#form').parsley({
        messages: {
            required: valueOrLabel + ' Error message',
            minlength: valueOrLabel + ' is too short'
        } 
    });
    $('#form').parsley('isValid');
}

updateMessage($('#name'));

$('input[type="text"]').on('keyup', function() {
    updateMessage($(this));
});

And the HTML:

<form id="form" action="#">
    <div class="row">
        <label for="name">Name:</label>
        <input id="name" type="text" placeholder="Your name" parsley-minlength="6" parsley-required="true" />
    </div>
    <div class="row">
        <input type="submit" value="Validate" />
    </div>
</form>
Doodlebot
  • 926
  • 5
  • 9
  • Interesting approach, but I was trying to make this sort of automatic. Your solution works for one input, but for two as in this fork http://jsfiddle.net/X8Nj3/ will not work. – Adrian Florescu Dec 17 '13 at 07:31
  • I had tried using parsley-error-message within the inputs before trying to destroy parsley. perhaps you could update each input's parsley-error-message and destroying parsley to update the error messages. If you just need the labels and not the values you could just provide a parsley-error-message for each input field. – Doodlebot Dec 17 '13 at 17:00
0

I've added another data- attribute, data-error-container="#elem" that could allow you directly in dom to specify where the error messages will have to be displayed.

More info here: http://parsleyjs.org/documentation.html#parsleyfield

quoted from @guillaumepotier answer Parsley.js - Displaying Errors in a Specified Element

Community
  • 1
  • 1
Mauro Dias
  • 1,083
  • 1
  • 11
  • 23