如何使用 jQuery validate 验证表单中的所有字段?
Posted
技术标签:
【中文标题】如何使用 jQuery validate 验证表单中的所有字段?【英文标题】:How to validate ALL fields in a form with jQuery validate? 【发布时间】:2021-11-08 18:04:17 【问题描述】:我有一个使用 jQuery validate 验证的 html 表单。 其中“#dati”是表格。 然后,当 success 函数结果为 true 时,一个按钮 (#prossimaDomanda),它是一个用于下一个滑动的 Swiper 按钮,应该从“禁用”类和道具中释放。当 jQuery 仅验证第一个字段时,成功函数的结果为 true,并且按钮被释放。但我只需要在验证 所有 字段时才会发生这种情况。 谢谢大家。
<form method="post" action="?mode=invia" id="dati" enctype="multipart/form-data">
<div id="reportErrori"></div>
<div class="swiper-container">
<div>
<?php include("include/inc_navbar_front.php")?>
</div>
<div class="swiper-wrapper">
<div class="swiper-slide">
<div class="colonna">
<p class="istruzioni" id="test"><strong><?php echo $suffisso ?></strong>Dopo aver inserito i tuoi dati, compila il <strong>questionario</strong><br />
Riceverai il mio <strong>preventivo</strong> tramite email. </p>
</div>
<div class="colonna">
<div class="form-question">
<label for="n2">Nome azienda</label>
<input type="text" id="n2" name="nomeAzienda">
</div>
<div class="form-question">
<label for="n3">Indirizzo</label>
<input type="text" id="n3" name="indirizzo" >
</div>
<div class="flex">
<div>
<div class="miniDomanda">
<label for="n4">Città</label>
<input type="text" id="n4"name="citta">
</div>
<div class="miniDomanda">
<label for="n5">Cap</label>
<input type="text" id="n5" name="cap" >
</div>
</div>
<div>
<div class="miniDomanda">
<label for="n6">Provincia</label>
<input type="text" id="n6" name="provincia">
</div>
<div class="miniDomanda">
<label for="n7">P.IVA</label>
<input type="text" id="n7" name="partitaIva" >
</div>
</div>
</div>
<div class="form-question">
<label for="n8">Indirizzo email</label>
<input type="text" name="email" id="n8">
</div>
<!--FORM immagini-->
<div class="form-question" id="immagini">
<label for="contenitore-immagini">Immagine<br />
<span style="font-size: 14px; font-style: italic; font-weight: 400; ">(puoi inserirne al massimo 3)</span></label>
<div class="immagini" id="contenitore-immagini">
<div class="newUpload" id="wrapButton">
<label for="immagineNuova" id="labelAggiungi">Aggiungi una foto</label>
<input type="file" id="immagineNuova" name="immagine[]" />
</div>
</div>
</div>
</div>
</div>
<div class="swiper-slide">
<h2>Il sondaggio durerà circa 30 minuti. Puoi seguire i progressi dalla barra sottostante</h2>
</div>
<?php
if ( $domande )
$k = 1;
foreach ( $domande as $row )
?>
<div class="swiper-slide slide-domanda">
<div class="form-question">
<h2>Domanda numero <strong><?php echo $k ?></strong></h2>
<label for="n5" class="areaTesto"><?php echo $row['testo_domanda']?></label>
<input type="hidden" name="id_domanda[]" data-counter="<?php echo $k?>" value="<?php echo $row['id_domanda']?>">
<textarea name="testo_risposta[]" id="contattiPrincipali" cols="30" rows="10"></textarea>
</div>
<?php if ($k == $contaDomande)?>
<div class="button-wrapper">
<button type="submit">Invia sondaggio</button>
</div>
<?php ?>
</div>
<?php
$k++;
;
;
?>
</div>
<div class="button-wrapper">
<button type="button" class="swiper-button-next disabled" disabled id="prossimaDomanda"><span class="fa fa-chevron-right"></span></button>
</div>
<div class="button-wrapper">
<button type="button" class="swiper-button-prev precedenteDomanda" id="precedenteDomanda"><span class="fa fa-chevron-left"></span></button>
</div>
</div>
<?php
;
;
?>
</form>
var n2, n3, n4, n5, n6, n7, n8;
function valore (selettore)
return $(selettore).val();
$("#n2").on("change", function()
n2 = valore("#n2");
console.log(n2);
)
$("#n3").on("change", function()
n3 = valore("#n3");
console.log(n3);
)
$("#n4").on("change", function()
n4 = valore("#n4");
console.log(n4);
)
$("#n5").on("change", function()
n5 = valore("#n5");
console.log(n5);
)
$("#n6").on("change", function()
n6 = valore("#n6");
console.log(n6);
)
$("#n7").on("change", function()
n7 = valore("#n7");
console.log(n7);
)
$("#n8").on("change", function()
n8 = valore("#n8");
console.log(n7);
)
$("#dati").validate(
rules:
nomeAzienda:
required: true,
remote:
url: "include/cms_ajax_pagina.php?mode=valida",
type: 'post',
data: n2: n2
,
pattern: /^(?=.2,$)(([0-9a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõőøùúûüųūűÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕŐØÙÚÛÜŲŪŰŸÝŻŹÑßÇŒÆČŠŽ∂ð ,\.\'\-\?\:])?(?!))+$/ ,
indirizzo:
required: true,
remote:
url: "include/cms_ajax_pagina.php?mode=valida",
type: 'post',
data: n3: n3
,
pattern: /^(?=.2,$)(([0-9a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõőøùúûüųūűÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕŐØÙÚÛÜŲŪŰŸÝŻŹÑßÇŒÆČŠŽ∂ð ,\.\'\-\?\:])?(?!))+$/ ,
cap:
required: true,
remote:
url: "include/cms_ajax_pagina.php?mode=valida",
type: 'post',
data: n4: n4
,
pattern: /^(?=.2,$)(([0-9a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõőøùúûüųūűÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕŐØÙÚÛÜŲŪŰŸÝŻŹÑßÇŒÆČŠŽ∂ð ,\.\'\-\?\:])?(?!))+$/ ,
citta:
required: true,
remote:
url: "include/cms_ajax_pagina.php?mode=valida",
type: 'post',
data: n5: n5
,
pattern: /^(?=.2,$)(([0-9a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõőøùúûüųūűÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕŐØÙÚÛÜŲŪŰŸÝŻŹÑßÇŒÆČŠŽ∂ð ,\.\'\-\?\:])?(?!))+$/ ,
provincia:
required: true,
remote:
url: "include/cms_ajax_pagina.php?mode=valida",
type: 'post',
data: n6: n6
,
pattern: /^(?=.2,$)(([0-9a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõőøùúûüųūűÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕŐØÙÚÛÜŲŪŰŸÝŻŹÑßÇŒÆČŠŽ∂ð ,\.\'\-\?\:])?(?!))+$/ ,
partitaIva:
required: true,
remote:
url: "include/cms_ajax_pagina.php?mode=valida",
type: 'post',
data: n7: n7
,
pattern: /^(?=.2,$)(([0-9a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõőøùúûüųūűÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕŐØÙÚÛÜŲŪŰŸÝŻŹÑßÇŒÆČŠŽ∂ð ,\.\'\-\?\:])?(?!))+$/ ,
email:
required: true,
remote:
url: "include/cms_ajax_pagina.php?mode=valida",
type: 'post',
data: n8: n8
,
pattern: /^(([a-zA-Z]|[0-9])|([-]|[_]|[.]))+[@](([a-zA-Z0-9])|([-]))2,63[.](([a-zA-Z0-9])2,63)+$/ ,
,
messages:
nomeAzienda:
required: "Campo obbligatorio",
pattern: "Caratteri ammessi: alfanumerici, accentate latine, spazio. Simboli ammessi: trattino(-), apostrofo ('), virgola(,), punto(.),punto interrogativo(?).",
remote: "Remote ko"
,
indirizzo:
required: "Campo obbligatorio",
pattern: "Caratteri ammessi: alfanumerici, accentate latine, spazio. Simboli ammessi: trattino(-), apostrofo ('), virgola(,), punto(.),punto interrogativo(?).",
remote: "Remote ko"
,
cap:
required: "Campo obbligatorio",
pattern: "Caratteri ammessi: alfanumerici, accentate latine, spazio. Simboli ammessi: trattino(-), apostrofo ('), virgola(,), punto(.),punto interrogativo(?).",
remote: "Remote ko"
,
citta:
required: "Campo obbligatorio",
pattern: "Caratteri ammessi: alfanumerici, accentate latine, spazio. Simboli ammessi: trattino(-), apostrofo ('), virgola(,), punto(.),punto interrogativo(?).",
remote: "Remote ko"
,
provincia:
required: "Campo obbligatorio",
pattern: "Caratteri ammessi: alfanumerici, accentate latine, spazio. Simboli ammessi: trattino(-), apostrofo ('), virgola(,), punto(.),punto interrogativo(?).",
remote: "Remote ko"
,
partitaIva:
required: "Campo obbligatorio",
pattern: "Caratteri ammessi: alfanumerici, accentate latine, spazio. Simboli ammessi: trattino(-), apostrofo ('), virgola(,), punto(.),punto interrogativo(?).",
remote: "Remote ko"
,
email:
required: "Campo obbligatorio",
pattern: "Inserisci un email valido.",
remote: "Remote ko",
,
invalidHandler: function(event, validator)
$("#prossimaDomanda").addClass("disabled");
$("#prossimaDomanda").prop("disabled", true);
console.log("form ko");
,
success: function()
$("#prossimaDomanda").removeClass("disabled");
$("#prossimaDomanda").prop("disabled", false);
,
errorPlacement:function(error, element)
var campo = element.parent();
campo.css("position", "relative");
$(".error-container").appendTo(campo);
error.appendTo($(".error-container"));
$(".error-container").fadeIn(300);
setTimeout(function()
$(".error-container").fadeOut(1000);
setTimeout(function()
campo.css("position", "static")
$(".error-container").empty();
$(".error-container").appendTo("body");, 1500)
, 4000);
,
submitHandler: function(form)
$(form).submit();
)
编辑: 这是通过 AJAX 启动的小 php 代码,它非常有效,但它不是那么稳定。有时,当我点击自动完成时,我会遇到同样的问题。
if ( $mode == "validazione" )
foreach($_POST as $risposta)
echo (isset($risposta)) ? "true" : "false";
另一个编辑:
最后,我又写了一个小脚本。也许它太冗长了,但它现在可以工作了。
function validaMioBottone (element)
var str = element.val();
if(str.length > 0)
var reg = new RegExp("(?=.2,$)(([0-9a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõőøùúûüųūűÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕŐØÙÚÛÜŲŪŰŸÝŻŹÑßÇŒÆČŠŽ∂ð ,\.\'\-\?\:])\2?(?!\2))+$")
var res = reg.test(str);
return res
else
return
var numeroOk = 0;
$("#dati input").each(function()
$(this).on("change", function()
if( validaMioBottone($(this)) == true )
if($(this).hasClass("validato"))
return
else
numeroOk++
$(this).addClass("validato");
else
if($(this).hasClass("validato"))
numeroOk--
$(this).removeClass("validato")
else
return
if(numeroOk == 7)
$("#prossimaDomanda").removeClass("disabled");
$("#prossimaDomanda").prop("disabled", false);
else
$("#prossimaDomanda").addClass("disabled");
$("#prossimaDomanda").prop("disabled", true);
console.log(numeroOk);
)
)
【问题讨论】:
首先,向我们展示实际的 RENDERED 代码,而不是 PHP。其次,表单的HTML在哪里? "... 成功函数结果为 true 并且按钮被释放。我只需要在验证所有字段时才会发生这种情况。" - 显然success
回调不是正确的位置,因为每次单个字段有效时都会调用它。试试submitHandler
,因为它只在整个表单有效时才被调用。
【参考方案1】:
$( "#register_form" ).validate(
rules:
password:
minlength: 8
,
email:
remote:
url: '% url "check_email_notexists" %', <--- you can also make an ajax call like this.
type: 'GET'
,
username:
minlength: 3,
maxlength: 25,
remote:
url: '% url "check_username_notexists" %',
type: 'GET'
,
confirm_password:
minlength: 8,
equalTo: "#password"
,
errorElement: 'small',
messages:
first_name:
required: "Please enter First Name"
,
last_name:
required: "Please enter Last Name"
,
username:
required: "Please provide a username",
remote: 'Username already exists'
,
email:
required: "Please provide an email",
remote: 'Email already exist'
,
password:
minlength: jQuery.validator.format("At least 0 characters required!"),
required: "Please enter Password"
,
confirm_password:
required: "Please enter Password",
equalTo: "Password did not match"
);
我在我的一个 jquery 项目中使用它。
【讨论】:
以上是关于如何使用 jQuery validate 验证表单中的所有字段?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 jQuery Validate 正确验证放置在多个选项卡上的 Twitter 引导表单?
如何在不提交的情况下使用 jQuery Validator 验证表单的第一部分?