jQuery validate , how to make validation rules for dynamically generated fields? - javascript

I have an HTML form with dynamically add more fields. For example company name. I am trying to use the jQuery validate method to validate. It is working fine with the existing company name field. Here is the code.
<script>
$("#company_creation_form").validate({
rules:{
company_name: {
required: true,
minlength: 3
}
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "<?php echo BASE_URL;?>crm/thankyou/",
data: $(form).serialize()+"&company_count="+company_count,
success: function () {
alert("thanks");
}
});
return false; // required to block normal submit since you used ajax
}
});
</script>
When I click on add more button another company name field will create on the form. The below code is failed to validate the dynamically generated field. Here I am getting the field count globally in this variable company_count
<script>
$("#company_creation_form").validate({
rules:{
company_name: {
required: true,
minlength: 3
},
I tried like below, but this is giving me error
if(company_count> 0){
var new_field = jQuery("#company_name"+company_count);
new_field : {
required: true,
minlength: 3
},
}
The above block code is showing error in the text editor it self
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "<?php echo BASE_URL;?>crm/thankyou/",
data: $(form).serialize()+"&company_count="+company_count,
success: function () {
alert("thanks");
}
});
return false; // required to block normal submit since you used ajax
}
});
</script>
Can anyone help me with how to make validation for these dynamically generated fields? Any help would be greatly appreciated. I am using form submission by using Ajax.
Code to add company fields dynamically
var company_room = 0;
var company_room1 = 0;
function add_another_company() {
company_room++;
company_room1++;
var objTo = document.getElementById('company_field')
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass2" + company_room);
//var rdiv = 'removeclass2' + company_room;
divtest.innerHTML = '<div class="form-row"><div class="col-sm-5"> <div class="form-group pad-tp-5"><input type="text" class="form-control aj4" id="company_name" name="company_name" placeholder="Company Name"></div></div><div class="col-sm-2"> <div class="form-group"> <button class="btn btn-danger bdr-rds-100 btn-pad" type="button" onclick="remove_another_company(' + company_room + ');"> <i class="fa fa-minus"></i> </button> </div></div></div>';
objTo.appendChild(divtest);
var E_fields = $('.aj4');
var E_count = 1;
$.each(E_fields, function() {
jQuery(this).attr('id','company_name' + E_count);
jQuery(this).attr('name','company_name' + E_count);
E_count++;
});
}
function remove_another_company(rid2) {
company_room1--;
$('.removeclass2' + rid2).remove();
var E_fields = $('.aj4');
var E_count = 1;
$.each(E_fields, function() {
jQuery(this).attr('id','company_name' + E_count);
jQuery(this).attr('name','company_name' + E_count);
E_count++;
});
}

OK, so I didn't have your HTML so I had to mock some up. You will obviously have to tweak this a little to work with your ID's. I tried to keep it as close as possible to the ID's/classes you were already using.
I removed the pure javascript functions and the onclick events in favor of jquery since you were already using it. Hopefully this kind of simplifies things a bit and makes it more manageable.
NOTE: I added a hidden input field to keep track of company count. This way it will be included when you $(form).serialize in your ajax options (as you are adding it with a variable now). I included code to preserve the company_count variable also, so basically you will have 2 company counts. I did this just to show you an easier way to keep track of this without having to micro manage it. :)
Try out this code and let me know what your getting in console if it is not working. Thanks
MOCK HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="form-wrapper">
<p>Dynamic Form</p>
<button id="addField">Add Dynamic Field</button>
<form id="dynForm">
Static Field: <input id="company_name" name="company_name" minlength="3" type="text" value="Static Company Name" required>
<br>
<input type="hidden" id="companyCount" name="companyCount" value="1">
<div id="company_field">
</div>
</form>
</div>
JQUERY/JS
$(function() { // <---- Document Ready!
$("#addField").on("click", () => {
var count = parseInt($("#companyCount").val(), 10);
count += 1;
$("#companyCount").val(count.toString());
var thisId = "company_name" + count.toString();
var html = '<div class="form-row"><div class="col-sm-5"> <div class="form-group pad-tp-5"><input type="text" class="form-control aj4" id="'+thisId+'" name="'+thisId+'" minlength="3" placeholder="Company Name" required></div></div><div class="col-sm-2"> <div class="form-group"> <button class="btn btn-danger bdr-rds-100 btn-pad" type="button"> <i class="fa fa-minus"></i> </button> </div></div></div>';
var ele = $.parseHTML(html);
$("#company_field").append(ele);
});
$("#company_field").on("click", "button", () => $(this).closest(".form-row").remove());
$("#company_creation_form").validate({
submitHandler: function(form) {
var company_count = parseInt($("#companyCount").val(), 10);
$.ajax({
type: "POST",
url: "<?php echo BASE_URL;?>crm/thankyou/",
data: $(form).serialize() + "&company_count=" + company_count,
success: function() {
alert("thanks");
}
});
return false;
}
});
});

Related

How to send POST requests from dynamic fields?

I'm creating a quiz form to pass into a JSON file, but I'm having trouble sending the POST requests. I'm not sure which fields I can access, or how.
This is the form: https://i.imgur.com/6xtmt3a.png
<script>
// input field
$(document).ready(function() {
var wrapper = $(".div1");
var newbutton = $(".add_form_field");
var fields = 1;
$(newbutton).click(function(e) {
e.preventDefault();
$(wrapper).append(' <div class="input-group"> <input type="text" value = "Question" class="form-control" placeholder="Recipients username" <div class="input-group-append" id="button-addon4"><button class="btn btn-outline-secondary" id ="delete" type="button">Delete</button><button class="btn btn-outline-secondary" id ="add" type="button">Add</button></div></div></div>'); //add input box
//$(wrapper).append('<button type="button" id ="test1" class="btn btn-primary">Primary</button>'); //add input box
//$(wrapper).append('<div><input type="text" value = "Question"name="mytext[]"/> Delete add </div> '); //add input box
var d = $(this).parent('form').serialize();
console.log(d);
});
//delete buttons
$(wrapper).on("click", "#delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
fields--;
})
// remove div
$(wrapper).on("click", '#s1', function(e) {
//$(this).parent('div').parent('div').remove();
var q= $(this).parent().serialize();
console.log(q);
})
//add answer
$(wrapper).on("click", "#add", function(e) {
e.preventDefault();
$(this).parent('div').append('\n <div class="input-group flex-nowrap"><div class="input-group-prepend"><span class="input-group-text" id="addon-wrapping">-</span></div><input type="text" class="form-control" placeholder="Answer" aria-label="Username" aria-describedby="addon-wrapping"></div> ' );
var d = $(this).parent('form').serialize();
console.log(d);
//$(this).parent('div').parent('div').append('<div class="input-group mb-3"><input type="text" class="form-control" placeholder="Recipients username" aria-label="Recipients username" aria-describedby="button-addon2"><div class="input-group-append"><button class="btn btn-outline-secondary" type="button" id="button-addon2">Button</button></div></div>' );
fields--;
})
});
$( "#quizForm" ).submit(function( event ) {
var $form = $( this ),
path = $form.attr( "action" );
payload = {"testKey":"test"};
var posting = $.ajax({
url: path,
method: "POST",
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: payload,
dataType: "application-json",
});
console.log(payload);
posting.done(function() {
console.log("posted");
});
});
</script>
I need to have a JSON file output on submit that contains the questions and answers to each question (right or wrong for now) Thanks!
I would suggest adding an attribute contains the object's key on each question - let's say it will be the "question ID".
we will have something like that:
<div class="question-container" question-id="01"></div>
Assuming that answers are an .answer div with an input inside we will have something like that on form submit:
let formObject = new Object();
$('.question-container')
.each(function () {
const questionID = this.attr('question-id');
const answersArray = new Array();
this.find('.answer input')
.each(function () { // assuming answer is a div contains an input tag
answersArray.push(this.value());
})
formObject[questionID] = answersArray;
})
/// here formObject contains the formatted form as json

Submitting 2 forms separately via AJAX - Python Flask

I'm trying to submit 2 separate forms via AJAX, but on submitting form2 I get a 500 bad request error.
My HTML code is below, but basically my page is a flask template that works as follows:
*User makes selections
*These selections are then posted via the submit button named "button" Value "Calculate Available Overall Heights".
*This runs some SQL query to determine a list of entries that are placed into a newly generated <select id="mySelect" class="form-control" onchange="myFunction()"></select>
This is done by JS which is also listed below as MyJS.js
OAH.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p class="h2">XXX</p>
<form method="post" id="form1">
<fieldset>
</div>
<div class="col-sm-3">
<span style="float:left"><label>Overall Height</label></span>
///my inputs, various selects etc ///
<div id="response">
<!-- Empty element until form submitted-->
</div>
<p id="ApertureHeight"></p>
<p id="ApertureHeightBelowPelmet"></p>
<p id="ApertureHeightUnderRoofSticks"></p><br>
<p id="OverallWidth"></p>
<p id="RearAppWidth"></p>
<p id="RearPillarNS"></p>
<p id="OAH"></p>
</div>
</fieldset>
<script src="/static/js/MyJS.js"></script>
</form>
<form method="post" id="form2">
<div class="col-sm-3">
<label>
<span style="float:left"><input type="text" id="myText" value=""></span>
</label>
<br>
<input type="button" value="Click Me!" onclick="submitForms()" />
</div>
</form>
</body>
</html>
form2 has a button called "Click Me!" which calls a function that submits form 2.
submitForms = function(){
document.getElementById("form2").submit();
};
MyJS.js
$("#form1").on("submit", function(event) {
$targetElement = $('#response');
event.preventDefault();
// Perform ajax call
//
console.log("Sending data: " + $(this).serialize());
$.ajax({
url: '/OAH',
data: $('form').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
// Success handler
var TableTing = response["table"];
$("#TableThing").empty();
$("#TableThing").append(TableTing);
for (key in response) {
if (key == 'myList') {
// Add the new elements from 'myList' to the form
$targetElement.empty();
select = $('<select id="mySelect" class="form-control" onchange="myFunction()"></select>');
response[key].forEach(function(item) {
select.append($('<option>').text(item));
});
$targetElement.html(select);
} else {
// Update existing controls to those of the response.
$(':input[name="' + key + '"]').val(response[key]);
}
}
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call
})
});
submitForms = function(){
document.getElementById("form2").submit();
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$("#form2").on("submit", function(event) {
event.preventDefault();
console.log("Sending data: " + $(this).serialize());
$.ajax({
url: '/OAH',
data: $('#form2').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call
})
});
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function myFunction() {
var FifthWheel = document.getElementById("FifthWheelHeight").value;
var NeckDepth = document.getElementById("NeckDepth").value;
var CantRailDepth = document.getElementById("CantRailDepth").value;
var RearTensioner = document.getElementById("RearTensioner").value;
var OAH = document.getElementById("mySelect").value;
if (CantRailDepth = 115) {
var PelmetDim = 100;
} else {
PelmetDim = 75;
}
var ApertureHeight = Number(OAH) - Number(FifthWheel) - Number(NeckDepth) - Number(CantRailDepth);
var ApertureHeightBelowPelment = Number(ApertureHeight) - Number(PelmetDim);
var ApertureHeightUnderRoofSticks = Number(OAH) - Number(FifthWheel) - Number(NeckDepth) - 35;
document.getElementById("ApertureHeight").innerHTML = "Aperture below Cantrail = " + ApertureHeight + "mm";
document.getElementById("ApertureHeightBelowPelmet").innerHTML = "Aperture below pelmet = " +
ApertureHeightBelowPelment + "mm";
document.getElementById("ApertureHeightUnderRoofSticks").innerHTML = "Aperture below roof sticks = " +
ApertureHeightUnderRoofSticks + "mm";
document.getElementById("OverallWidth").innerHTML = "Overall Width = 2548mm (2550mm on spec)";
document.getElementById("OAH").innerHTML = OAH;
document.getElementById("myText").value = document.getElementById("OAH").innerHTML;
}
I need this form to submit separately, via AJAX without refreshing the page, as I need the JSON array to be able to calculate further stuff that will be passed into Python Flask. My issue is I am getting a bad request when submitting form2.
Anyone got any ideas on what I have done wrong?
I think you are using the same endpoint URL to try handle 2 different requests. The 2nd form does not send the correct data and you're then getting Server errors. Try creating another endpoint on your python flask server for handling form2 and the myText field value.

User input does not get captured/stored

I am trying to figure out why this onclick function in my JavaScript and Jquery code are not working.
I am referring my "userInput" in the JavaScript code and storing it in a variable called "userDate". For some reason, the user input does not get captured/stored.
This is my HTML:
<form role="form">
<p> Enter the date:
<input id="userInput" type="text" placeholder="yyyy-mm-dd" autofocus required></p>
<button id="convert" type="submit" class="btn btn-primary btn-lg" padding="center">
<span class="glyphicon glyphicon-euro"></span>
</button>
</form>
This is my JS code:
$(function () {
// cache the DOM element
var $currencies = $("#currencies");
var $userInput = $("#userInput");
// We are listening on the 'document',
// for a click on an element with an ID of #convert in the HTML
$("#convert").on("click", function() {
var userDate = $userInput;
// testing
console.log(userDate);
alert ("Handler for .click() is called.");
// AJAX call for GET request
$.ajax({
type: 'GET',
url: 'http://xxx.xx',
success: function(currencies) {
console.log("success func is called");
console.log(userDate);
$.each(currencies, function(i, currency){
$currencies.append("<div> EUR: " + currencies.rates["EUR"] + ", date: " + currencies.date + "</div>");
});
},
// error handling for my request
error: function() {
alert("error loading currencies");
}
});
});
});
change
var userDate = $userInput;
to
var userDate = $userInput.val();
$userInput is a reference to the jquery object holding the input element. Using .val() returns the text value of that input element.

How to distinguish which button was clicked in the html form and based on that pass different values with ajax?

I have the following html form:
<form class="center" id="myform">
<p>
<input id="email" name="email" type="email" class="textox email" title="" placeholder="your#email.com" required>
</p>
<textarea name="slogan" id="textarea" maxlength="140" style="resize:none" class="textoxarea" title="Please enter at least 5 characters" placeholder="Placeholder" ></textarea>
<div class="terms">
<input type="checkbox" class="required" value="None" id="terms" name="terms">I accept terms</input>
</div>
</p>
<input type="submit" id="sendfeedback" value="now" disabled/>
<input id="datetimepicker" type="text" readonly="readonly">
<input type="submit" id="postmelater" value="send" disabled/>
</form>
And as you can see above, I have a form with two buttons. The logic behind it works like that, that when I want to put text to database with current timestamp - I choose button sendfeedback. However, there's also a possibility of adding the feedback with chosen timestamp, that is happening when user choses the date from datetimepicker and hits postmelater. Now, the ajax code for that looks like this:
$(document).ready(function () {
$('#myform').validate({// initialize the plugin
errorElement: 'div',
rules: {
email: {
required: true,
email: true
},
slogan: {
required: true,
minlength: 2
},
terms: {
required: true,
maxlength: 2
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
var mail = $("#email").val(); //mg
var text = $("#textarea").val();
var date = 0;
var stand = 1;
$.ajax({
url: 'savedatanow.php'
type: "POST",
data: {
mail: mail,
text: text,
date: date,
stand: stand
},
success: function(response)
{
alert(response);
}
});
}
});
$('#myform').find('input, textarea').on('change', function () {
var btn = $('#myform').find('input[type=submit]');
if ($('#myform').valid()) {
btn.removeAttr('disabled');
} else {
btn.attr('disabled', 'disabled');
}
});
});
There's a validation process attached to the fields and so far - only support for the first button. How can I add a support for 2nd button, and in case when user clicks it - also pass the datetime attribute to ajax? Can I distinguish them somehow in Ajax? Thanks!
Here depends on functionality of validation plugin, when it reacts, but likely you can try to add onclick to buttons which sets some hidden variable, indicating which button was pushed. Like this:
<input type="submit" id="sendfeedback" onclick="this.form.clickedbtn.value=1" value="now" disabled/>
<input type="submit" id="postmelater" value="send" onclick="this.form.clickedbtn.value=2" disabled/>
and also add hidden input to the form like this
<input type="hidden" id="clickedbtn" name="clickedbtn">
Than in the handler add
var clickedbtn = $("#textarea").val();
...
clickedbtn: clickedbtn,
so form will look like this:
<form class="center" id="myform">
<input type="hidden" id="clickedbtn" name="clickedbtn">
<p>
<input id="email" name="email" type="email" class="textox email" title="" placeholder="your#email.com" required>
</p>
<textarea name="slogan" id="textarea" maxlength="140" style="resize:none" class="textoxarea" title="Please enter at least 5 characters" placeholder="Placeholder" ></textarea>
I accept terms
</p>
<input type="submit" id="sendfeedback" value="now" onclick="this.form.clickedbtn.value=1" disabled/>
<input id="datetimepicker" type="text" readonly="readonly">
<input type="submit" onclick="this.form.clickedbtn.value=2" id="postmelater" value="send" disabled/>
</form>
And handler will look like this:
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
var mail = $("#email").val(); //mg
var text = $("#textarea").val();
var date = 0;
var stand = 1;
var clickedbtn = $("#textarea").val();
$.ajax({
url: 'savedatanow.php'
type: "POST",
data: {
mail: mail,
text: text,
date: date,
clickedbtn: clickedbtn,
stand: stand
},
success: function(response)
{
alert(response);
}
});
}
After that in php script you can check
if ($_POST["clickedbtn"]==1) {
send now code
} else {
other code
}
Change
$('#myform').find('input, textarea').on('change', function () {
var btn = $('#myform').find('input[type=submit]');
if ($('#myform').valid()) {
btn.removeAttr('disabled');
} else {
btn.attr('disabled', 'disabled');
}
});
to
$('#myform').find('input, textarea').on('change', function () {
var sendfeedbackbtn = $('#sendfeedback');
var postmelaterbtn = $('#postmelater');
var datepicker = $('#datetimepicker');
if ($('#myform').valid()) {
sendfeedbackbtn.removeAttr('disabled');
datepicker.removeAttr('readonly');
if (isTimeValid()) {
postmelaterbtn.removeAttr('disabled');
}
} else {
datepicker.attr('readonly', 'readonly');
sendfeedbackbtn.attr('disabled', 'disabled');
postmelaterbtn.attr('disabled', 'disabled');
}
});
So it enables the sendfeedback and the timestamp input area. And if not valid, all button and timestamp area will be disabled.
Then add
$('#myform').find('#datetimepicker').on('change', function () {
var postmelaterbtn = $('#postmelater');
var datepicker = $('#datetimepicker');
// Need to implement isTimeValid method.
if ($('#myform').valid() && isTimeValid()) {
postmelaterbtn.removeAttr('disabled');
} else {
postmelaterbtn.attr('disabled', 'disabled');
}
});
So when the timestamp area is changed, check if its valid (need implement isTimeValid), and decide whether to make postmelater able to clicked or not.
And your submit handler should be:
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
var mail = $("#email").val(); //mg
var text = $("#textarea").val();
// Decide to send a timestamp data or not.
var timestamp = $('#datetimepicker').attr('readonly') ? null : $('#datetimepicker').val();
var date = 0;
var stand = 1;
$.ajax({
url: 'savedatanow.php',
type: "POST",
data: {
mail: mail,
text: text,
date: date,
stand: stand
// So this value will be null or whatever your input
timestamp: timestamp
},
success: function(response)
{
alert(response);
}
});
}
And you can decide PHP side's behavior on whether the given timestamp is a null value or not.
As you give all these inputs an id, I directly use its id selector to get them, but you can still change to other selector at wish.
You could use js/php to set the default value of your date field to be current date. That way you would only need one submit button:
<input type="date" value="<?php echo date("Y-m-d")?>">
or
<input type="date" id="datefield">
<script>
document.getElementById("datefield").value = new Date().getFullYear()+"-"+("0"+(new Date().getMonth()+1)).slice(-2)+"-"+("0" + new Date().getDate()).slice(-2);
</script>
But if you absolutely want to have two buttons, you could do:
<input type="button" onClick="firstButton()">
<input type="button" onClick="secondButton()">
and
function firstButton(){
//do what you need to
document.getElementsByTagName("form")[0].submit();
}
...and same for button two.

Error in the validation form blank textarea with jquery validate and ajax post form

I have a spring project and a task to register a comment on a particular system design.
The form of the page is as follows:
<form id="formularioCadastroComentario" role="form" method="POST" class="form-horizontal">
<input type="hidden" id="projeto" name="projeto" value="${projeto.id}"> <input type="hidden" id="usuario" name="usuario" value="${usuario.id}">
<input type="hidden" id="usuario_nome" name="usuario" value="${usuario.nome}"> <label class="control-label"for="textocomentarioInput"><h3>Novo Comentário</h3></label>
<div class="form-group">
<div class="input-group">
<textarea id="textocomentarioInput" name="texto" class="form-control" placeholder="Comentário" required="required"></textarea>
</div>
</div>
<br> <input name="botao" id="botaoEnviarComentario" class="btn btn-primary" value="Enviar" />
</c:url>" class="btn btn-default">Voltar
</form>
In my jsp page has the script link for the file funcoes.js, and the funcoes.js has the ajax function for insert a comment after a submit the form:
$("#formularioCadastroComentario").submit(function(e) {
var idProjeto = $('#projeto').val();
var idUsuario = $('#usuario').val();
var nomeUsuario = $('#usuario_nome').val();
var cabecalho = "Comentários do Projeto";
var textoComentario = $('#textocomentarioInput').val();
var data = new Date();
var dataFormatada = ("0" + data.getDate()).substr(-2)+ "-" + ("0" +(data.getMonth()+ 1)).substr(-2)+ "-"+ data.getFullYear()+ " "+ ('0' + data.getHours()).slice(-2)+ ":"+ ('0' + data.getMinutes()).slice(-2);
$.ajax({
type : "POST",
data : {
idProjeto : idProjeto,
idUsuario : idUsuario,
texto : textoComentario
},
url : "/gpa-pesquisa/comentario/comentarProjeto",
dataType : "html",
success : function() {
$('#comentarioList').prepend(
'<li class="well">'
+ '<div class="nome_usuario">'
+ nomeUsuario+ '</div>'
+ '<div class="corpo_texto">'
+ textoComentario + '</div>'
+ '<div class="formatacao_data">'
+ dataFormatada + '</div>'
+ '</li>');
$("#headComentarios").show();
}
});
$("#formularioCadastroComentario")[0].reset();
});
Im my JSP page has the jquery validate code after the close html tag body:
<script type="text/javascript">
$(document).ready(function($) {
$("#formularioCadastroComentario").validate({
rules : {
texto : {
minlength : 5,
required : true,
}
},
messages : {
texto : {
required : "Campo obrigatório",
minlength : "O campo deve ter no mínimo 5 caracteres"
}
},
highlight : function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight : function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement : 'span',
errorClass : 'help-block',
errorPlacement : function(error, element) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
});
The problem is that when I try to post a new comment under 5 letters or with blanks jquery validate the message appears, but if I submit the form code makes registering a new comment.
I wonder how I do to validate jquery ajax not working before to leave comments User registering with less than 5 letters or blanks.
Thank you,
You're supposed to put the ajax code within the submitHandler callback function of the .validate() method, not within your own .submit() handler.
$(document).ready(function($) {
$("#formularioCadastroComentario").validate({
submitHandler: function(form) {
var idProjeto = $('#projeto').val();
// the rest of your ajax function...
....
return false; // block the default submit
},
rules : {
texto : {
minlength : 5,
required : true,
}
},
......
Documentation:
submitHandler : Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it is validated.
BTW, you don't need to declare your rules in two places. Since you already have required: true specified within the .validate() method, you will not need the required="required" attribute on the corresponding elements.

Categories