gpt4 book ai didi

javascript - 如何在使用js提交之前验证表单?

转载 作者:行者123 更新时间:2023-12-03 07:37:07 27 4
gpt4 key购买 nike

我正在制作一个联系表单,其中我设置了必需的属性,但即使该字段中没有信息,它仍然会继续发送。我正在验证我的字段,如下所示:

<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);
});

注释:

  • 您可以考虑使用验证库或插件来简化工作。
  • 您可能需要添加类来设置有效/无效输入的样式,据我所知 Safari 不会渲染 :valid:invalid 伪类。
  • 也在服务器上执行验证。

关于javascript - 如何在使用js提交之前验证表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35563430/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com