之前写过一篇Post用Ajax查询用户名是否重名这次我们用JQuery的插件validate来实现更加简单相比之前用xmlhttprequest来说不用考虑浏览器兼容的问题这也是使用是Jquery这个轻量级框架的特点之一
此处用的是ASPNET MVC RCaspx代码如下
<%@ Page Language=C# AutoEventWireup=true CodeBehind=TestValidationaspxcs Inherits=DemoMVCFormViewsFormDemoTestValidation %>
<!DOCTYPE html PUBLIC //WC//DTD XHTML Transitional//EN >
<html xmlns= >
<head runat=server>
<title>Demo</title>
<script src=minjs type=text/javascript></script>
<script src= type=text/javascript></script>
<script type=text/javascript>
$(document)ready(function() {
$(#formsignup)validate({
rules: {
login: {
required: true
//here invoke related action
remote: <%=UrlAction(IsLoginAvailable FormDemo) %>
}
}
messages: {
login: {
required: 请输入用户名
remote: jQueryformat({} 已经有人用了)
}
}
// set this class to errorlabels to indicate valid fields
success: function(label) {
// set as text for IE
l( )addClass(checked)
}
})
})
</script>
</head>
<body>
<form action=<%=UrlAction(Register FormDemo)%> method=post id=formsignup>
<h>Demo表单</h>
<table id=inputArea>
<tr>
<td>用户名 (试试输入 Petter)</td>
<td><input type=text name=login id=login /></td>
</tr>
<tr>
<td colspan= align=center><br /><input type=submit /></td>
</tr>
</table>
</form>
</body>
</html>
MVC支持Json所有返回Json的结果直接使用是JsonResult看代码cs很简单
cs
/// <summary>
/// FormDemoController
/// </summary>
/// <remark>Author : PetterLiu : DEVLIUJUNYUAN</remark>
public class FormDemoController : Controller
{
public JsonResult IsLoginAvailable(string login)
{
//TODO: Do the validation
JsonResult result = new JsonResult()
if (login == Petter)
resultData = false;
else
resultData = true;
return result;
}
}