![](/img/trans.png)
[英]How do I stop Javascript form validate submitting before json response has returned?
[英]How do I validate a form before submitting with js?
我正在使用联系表单,在其中我已设置了必填属性,但是即使该字段中没有信息,它仍会继续发送。 我正在验证我的字段,如下所示:
<input type="text" name="grado" id="grado" placeholder="Grado a cursar" required oninvalid="this.setCustomValidity('Por favor, llena todos los campos')" oninput="setCustomValidity('')"/>
而我的js:
<script>
$("#contactForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
$submit = $form.find( 'button[type="submit"]' ),
grado_value = $form.find( 'input[name="grado"]' ).val(),
url = $form.attr('action');
/* Send the data using post */
var posting = $.post( url, {
grado: grado_value,
});
posting.done(function( data ){
/* Put the results in a div */
$( "#contactResponse" ).html(data);
/* Change the button text. */
$submit.text('Enviado');
/* Disable the button. */
$submit.attr("disabled", true);
});
});
</script>
提交之前有什么方法可以验证表格?
Safari不管其有效性如何都提交表单,因此您不能依赖浏览器验证。 我目前无法在Safari上进行测试,但是此替代方法应该可以使用。 它基于您的代码,但不使用验证:
首先,在表单中设置novalidate
属性
<form id="contactForm" novalidate>
<input type="text" name="grado" id="grado" placeholder="Grado a cursar" required />
<button type="submit">Send</button>
</form>
然后在提交事件处理程序中检查有效性,并根据需要显示/隐藏错误:
$("#contactForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
$submit = $form.find( 'button[type="submit"]' ),
grado_value = $form.find( 'input[name="grado"]' ).val(),
url = $form.attr('action');
if (!event.target.checkValidity()) {
// the form is not valid
// show some nice errors, I'm just changing the button text here
$submit.text('wrong');
return false;
}
// send your data here, the form should be valid
$submit.text('Enviado');
$submit.attr("disabled", true);
});
笔记:
:valid
和:invalid
伪类。 您必须return: false;
以防止其发送。
例:
$("#contactForm").submit(function (event) {
var valid = false;
// ... validation ... if data is valid, set valid to true
if (!valid) return false;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.