javascript 提交前如何进行ajax表单验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26072754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ajax form validation before submit how?
提问by user3788491
I am doing ajax cross domain request to my php page on server. I am posting form from html via ajax to my php page on server. Have problem with validation in client side.
我正在对服务器上的 php 页面执行 ajax 跨域请求。我正在通过 ajax 将表单从 html 发布到服务器上的 php 页面。客户端验证有问题。
I don't know how to do validation in client side before send form.
我不知道如何在发送表单之前在客户端进行验证。
html form is standard form, posting input fields: name, last name, message.... My html form, client side:
html 表单是标准表单,发布输入字段:姓名、姓氏、消息……我的 html 表单,客户端:
<script type="text/javascript">
var output = $('.nesa');
$(document).ready(function(){
$("#form1").submit(function (e) {
e.preventDefault();
$.ajax({
url: 'http://www.example.com/form.php',
crossDomain: true, //set as a cross domain requests
type: 'post',
data: $("#form1").serialize(),
beforeSend: function (){
// add spinner
$('.spinner').append('<img id="animacija" src="spinnersmall.gif" alt="Loading" />');
},
success: function (data) {
$(".nesa").html(data);
alert("sent " + data);
},
error: function(){
output.text('Message is not sent!');
}
});
});
});
How to to validation? I try to put code in beforeSend but without success. Or maybe to use submitHandler?
如何验证?我尝试将代码放入 beforeSend 但没有成功。或者也许使用 submitHandler?
Idea is when user click submit, that validation start, and if fails to tell "insert your email address". Now when i click submit it send data to server. I want that first check input fields.
想法是当用户单击提交时,验证开始,如果未能告诉“插入您的电子邮件地址”。现在,当我单击提交时,它会将数据发送到服务器。我希望首先检查输入字段。
This form is actual working it sending data to server, but just need to figure out how to do validation. Where to put validation in ajax call?
这个表单实际上是在向服务器发送数据,但只需要弄清楚如何进行验证。将验证放在 ajax 调用中的何处?
Thanks
谢谢
回答by Mohd. Shaukat Ali
Create a function to validate form which return true/false. Call the function just before the $.ajax. check if return is false then return.. see the example below...
创建一个函数来验证返回真/假的表单。在 $.ajax 之前调用该函数。检查返回是否为假然后返回..见下面的例子......
if(!validateForm())
return false;
回答by Dorvalla
I always validate them right before I enter them into an AJAX call. Here is my exampel
我总是在将它们输入 AJAX 调用之前验证它们。这是我的例子
$('#form_nieuwsbrief').bind('submit',function(){
var name = $('input[name=naamNieuwsbrief]').val();
var email = $('input[name=emailNieuwsbrief]').val();
var proceed = true;
if (name==""){
$('input[name=naamNieuwsbrief]').css({'border':'2px solid red'});
proceed = false;
}
if (email==""){
$('input[name=emailNieuwsbrief]').css({'border':'2px solid red'});
proceed = false;
}
if(proceed == false){
$("#msg").append("<div class='alert alert-danger' role='alert'>U bent informatie vergeten in te vullen.</div>");
setTimeout(function(){
$('.alert').fadeOut(400, function(){
$(this).remove();
})
;},10000
);
}
if(proceed == true){ // make the ajax call
This is just a quick one for a newsletter that just requests name and email. But the principle is the same. Just before you make an ajax call, create the if else statement with a variable you set if something is false. else you stick it tot he original validation, thus you can proceed.
对于只要求姓名和电子邮件的时事通讯来说,这只是一个快捷方式。但原理是一样的。就在您进行 ajax 调用之前,使用您设置的变量创建 if else 语句,如果某些内容为 false。否则,您将其粘贴到原始验证中,因此您可以继续。
回答by Michael Soriano
You're already validating via server side correct? Why don't you use that same validation rules to appear like your client side - via Ajax. I have a tutorial on how to do that:
您已经通过服务器端进行验证,对吗?为什么不使用相同的验证规则来显示像您的客户端 - 通过 Ajax。我有一个关于如何做到这一点的教程:
回答by Vimal Baisla
Please validate the form before sending ajax request. If there is no error then ajax request should be send otherwise return false. You can do like:
请在发送 ajax 请求之前验证表单。如果没有错误,则应发送 ajax 请求,否则返回 false。你可以这样做:
$("#form1").submit(function (e) {
e.preventDefault();
// Get the Login Name value and trim it
var name = $.trim($('#name').val());
// Check if empty of not
if (name === '') {
alert('Text-field is empty.');
return false;
}
});
You can see the demo Here's (http://jsfiddle.net/LHZXw/1/)
你可以在这里看到演示(http://jsfiddle.net/LHZXw/1/)
You can also make a function onKeyup.
您还可以创建一个 onKeyup 函数。
回答by danijar
First, are you actually using an AJAX form?
首先,你真的在使用 AJAX 表单吗?
You explained that you load the form itself via AJAX, but do you send it that way, too? It looks to me that you're trying to send it the HTML way. You can hook into the click
eventof the send button before you send the form. However, since the button is added to the page at runtime, you need to register the event to document
.
您解释说您通过 AJAX 加载表单本身,但是您也以这种方式发送吗?在我看来,您正在尝试以 HTML 方式发送它。您可以在发送表单之前挂钩发送按钮的click
事件。但是,由于按钮是在运行时添加到页面中的,因此您需要将事件注册到document
.
$(document).on('click', 'input[type=submit]', function() {
// Validate form
// Add error message on fail, and return
// Else submit form via AJAX
});
In either case, you can use jQuery's blur
eventas an alternative to validate each field when the user jumps to the next. You could even validate every time the user presses a key with keypress
.
在任何一种情况下,您都可以使用jQuery 的blur
事件作为替代,以便在用户跳转到下一个字段时验证每个字段。您甚至可以在用户每次按下带有keypress
.