我想使用parsley js验证表单,并使用twitter的bootstrap工具提示显示错误(如果有的话)。
我读了这篇link关于与bootley的twitter bootstrap集成以及关于EventListeners的stackoverflow question。但是,我仍然无法显示错误消息。
这就是我实施它的方式
...
<input id="id_email" name="email" required=True parsley-type="email">
<button type="submit" onclick="javascript:$('#id_email').parsley(parsleyOptions); ">Next</button>
...
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="{% static "js/bootstrap.min.js" %}"></script>
<script type="text/javascript" src="{% static "js/parsley/parsley.js"%}"></script>
...
<script>
// parsley option
var parsleyOptions = {
// Sets success and error class to Bootstrap class names
successClass: 'has-success',
errorClass: 'has-error',
// Bootsrap needs success/error class to be set on parent element
errors: {
classHandler: function(el) {
return el.parent();
},
// Set these to empty to make sure the default Parsley elements are not rendered
errorsWrapper: '',
errorElem: ''
},
listeners: {
// Show a tooltip when a validation error occurs
onFieldError: function (elem, constraints, parsleyField) {
elem.tooltip({
animation: false,
container: 'body',
placement: 'top',
title: elem.data('error-message')
});
},
// Hide validation tooltip if field is validated
onFieldSuccess: function(elem, constraints, parsleyField) {
elem.tooltip('destroy');
}
}
};
</script>
...
工具提示不会在表单字段中触发错误(即使是空字段,也不会引发错误)。如何让欧芹触发工具提示工作?
附注:
答案 0 :(得分:4)
对于那些对使用parsley 2.x实现此目的感兴趣的人:
<form method="post" id="myForm">
<input id="id_email" name="email" class="required" data-parsley-type="email">
<button type="submit">Next</button>
</form>
<script type="text/javascript">
$(document).ready(function() {
// instanciate parsley and set the container
// as the element title without a wrapper
$("#myForm").parsley({
errorsContainer: function (ParsleyField) {
return ParsleyField.$element.attr("title");
},
errorsWrapper: false
});
// when there is an error, display the tooltip with the error message
$.listen('parsley:field:error', function(fieldInstance) {
var messages = ParsleyUI.getErrorsMessages(fieldInstance);
fieldInstance.$element.tooltip('destroy');
fieldInstance.$element.tooltip({
animation: false,
container: 'body',
placement: 'top',
title: messages
});
});
// destroy tooltip when field is valid
$.listen('parsley:field:success', function(fieldInstance) {
fieldInstance.$element.tooltip('destroy');
});
});
</script>
我使用的是Bootstrap 3.2.0和Parsley.js 2.0.2。我已经创造了一个小提琴:http://jsfiddle.net/C96ab/3/