使用ParsleyJS在自定义错误消息中标记

时间:2015-07-30 13:07:44

标签: jquery parsley.js

我正在使用ParsleyJS验证表单。 我也使用这种语法使用自定义错误消息:

<input type="text" id="qd-amount" data-parsley-required="true" data-parsley-required-message="This field is required">

这很好但我想在消息中添加一些标记,比如将用户发送到帮助部分的链接。我尝试过这样的事情:

 <input type="text" id="qd-amount" data-parsley-required="true" data-parsley-required-message="<a href=\"someurl\">Click here for help</a>">

但这似乎打破了表格的标记。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

You should probably use ' instead of " inside your <a> element. You should always escape HTML characters. If you're using PHP use htmlentities() or find a similar method in the server side language you're using or use a javascript method.

Something like this:

$(document).ready(function() {
    $("form").parsley();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.1.2/parsley.js"></script>

<form>
    <input type="text" id="qd-amount" data-parsley-required="true" data-parsley-required-message="<a href=&quot;http://google.com&quot;>Click here for help</a>" />
    <input type="submit" />    
</form>


Edit: following Alex's comment, Parsley allows you to customize messages by data attributes. Other than that you can create a custom validator via javascript for this purpose, but since OP only wanted a custom message for a required field I'm not sure this is worth the trouble.

The custom message in the data attribute will always need to be escaped, either manually or via a function that escapes HTML characters (either in a server side language or javascript).

For purposes of completeness, here are two examples, one with the quotes escaped and the other with a custom validator. Beware this code is using the latest Parsley version - 2.8.1

window.Parsley.addValidator('custom', {
    requirementType: 'string',
    validateString: function(value) {
        return value.length !== 0;
    },
    messages: {
        en: '<a href="http://google.com">so called "noobs" -  Click here for help for other field</a>'
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.8.1/parsley.min.js"></script>

<form data-parsley-validate="">
    <input type="text" id="qd-amount" data-parsley-required="true" data-parsley-required-message="<a href=&quot;http://google.com&quot;>so called &quot;noobs&quot; -  Click here for help</a>" />
    <input type="text" id="other-qd-amount" data-parsley-validate-if-empty data-parsley-custom=""/>
    <input type="submit" />    
</form>