我正在处理一个联系表单,我在其中设置了必需的属性,但即使该字段中没有信息,它也会继续发送。我正在验证我的字段:
<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>
在提交之前有没有办法验证表格?
答案 0 :(得分:1)
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
伪类。答案 1 :(得分:0)
您必须return: false;
才能阻止其发送。
示例:
$("#contactForm").submit(function (event) {
var valid = false;
// ... validation ... if data is valid, set valid to true
if (!valid) return false;
});