[英]How do I validate a form before submitting with js?
I'm working on a contact form in which I have set the required attribute but it keeps sending anyway even if the field has no info in it. 我正在使用联系表单,在其中我已设置了必填属性,但是即使该字段中没有信息,它仍会继续发送。 I'm validating my fields like this:
我正在验证我的字段,如下所示:
<input type="text" name="grado" id="grado" placeholder="Grado a cursar" required oninvalid="this.setCustomValidity('Por favor, llena todos los campos')" oninput="setCustomValidity('')"/>
And my js: 而我的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>
Is there any way to validate form before submitting? 提交之前有什么方法可以验证表格?
Safari submits the form regardless its validity, so you cannot rely on browser validation. Safari不管其有效性如何都提交表单,因此您不能依赖浏览器验证。 I'm not able to test on Safari right now, but this workaround should work.
我目前无法在Safari上进行测试,但是此替代方法应该可以使用。 It's based on your code but does not use the validation:
它基于您的代码,但不使用验证:
First, set the novalidate
attribute in your form 首先,在表单中设置
novalidate
属性
<form id="contactForm" novalidate>
<input type="text" name="grado" id="grado" placeholder="Grado a cursar" required />
<button type="submit">Send</button>
</form>
Then check for validity in the submit event handler and show/hide errors as needed: 然后在提交事件处理程序中检查有效性,并根据需要显示/隐藏错误:
$("#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);
});
Notes: 笔记:
:valid
and :invalid
pseudo-classes. :valid
和:invalid
伪类。 You have to return: false;
您必须
return: false;
to prevent it from sending. 以防止其发送。
Example: 例:
$("#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.