jQuery Form Plugin (三) :验证Form表单和文件上传
validation示例
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My Jquery</title>
<script type="text/javascript" src="<%=request.getContextPath()%>/jslib/jquery-1.4.2.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/jslib/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#validationForm').ajaxForm( { beforeSubmit: validate } );
});
function validate(formData, jqForm, options) {
for (var i=0; i < formData.length; i++) {
if (!formData[i].value) {
alert('Please enter a value for both Username and Password');
return false;
}
}
alert('Both fields contain values.');
}
</script>
</head>
<body>
<form id="validationForm" action="index.jsp" method="post">
Username:<input type="text" name="username" />
Password:<input type="password" name="password" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
注:其中validate()函数内部的处理方式还有另外两种:
1).function validate(formData, jqForm, options) {
var form = jqForm[0];
if (!form.username.value || !form.password.value) {
alert('Please enter a value for both Username and Password');
return false;
}
alert('Both fields contain values.');
}
2).function validate(formData, jqForm, options) {
var usernameValue = $('input[name=username]').fieldValue();
var passwordValue = $('input[name=password]').fieldValue();
if (!usernameValue[0] || !passwordValue[0]) {
alert('Please enter a value for both Username and Password');
return false;
}
alert('Both fields contain values.');
}
文件上传的示例和表单提交是一样的,详见官方资料!