I am looking for a way to include the jquery validation rules dynamically, because I need to use them in different places.
The user can edit for example a news in two ways. The first way is a usual form with jquery validation. This is no problem, its all working fine. But I also want to use the jquery validation with jeditable without repeating my rules.
So at the moment I have a NewsValidator.js like this:
$("form").validate({
rules: {
title: {
required: true,
rangelength:[3,50],
},
content: {
required: true,
rangelength: [25, 250]
}
},
});
And my code for the jeditable field looks like this:
$('.edit').editable('http://localhost/news/ajax', {
'id': 'news_id',
'name':'title',
'method': 'put',
submitdata : {
_method: "PUT",
content: $("div.content").text(),
},
error: function(){
alert('Something went wrong');
},
onsubmit: function(settings, td) {
$.getScript('../../js/validation/NewsValidator.js'); //-> this is not working (unexspected ) )
}
});
So does anyone know how I can use my validator inside the onsubmit function without copy&paste to keep it DRY?
Thanks in advance.
if ($("form").valid())in theonsubmithandler.$.getScriptonly after the user submits something. I suggest you just add<script src="../../js/validation/newsValidator.js">to the page, so it loads always.$(this).validate()does not even make any sense in the context of the code you've shown us. And you cannot call.validate()multiple times on the same form. It's called once on DOM ready to initialize the plugin on your form, and any subsequent calls are ignored. In other words, you cannot repeat.validate()even if you wanted. That's why the developer provides methods such as.rules('add')in order to dynamically manipulate the setup.