数据验证特性
RequiredAttribute
:表示数据不能为空RegularExpressionAttribute
:正则校验CompareAttribute
:和某个属性比较RangeAttribute
:表示在某个区间之内MaxAttribute
:最大值MinAttribute
:最小值StringLengthAttribute
:验证字符串长度DataTypeAttribute
:验证数据类型
在
Models
页面下面新建实体类UserInfo.cs
using System.ComponentModel.DataAnnotations;
namespace WebApplication1.Models
{
public class UserInfo
{
[Required(ErrorMessage ="用户名不能为空")]
[StringLength(10,ErrorMessage ="密码的长度不能超过10位")]
public string Username { set; get; }
[StringLength(6)]
public string Password { set; get; }
}
}
新建
TestController
并给Index
方法添加视图
@model UserInfo
@{
ViewData["Title"] = "Index";
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Index</title>
@* 需要引入以下文件 *@
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
</head>
<body>
<form asp-action="postData" method="post">
<table>
<tr>
<td>用户名:</td>
<td>
@Html.TextBoxFor(m => m.Username)
@* 客户端数据验证 *@
@Html.ValidationMessageFor(m => m.Username)
</td>
</tr>
<tr>
<td>用户名:</td>
<td>
@Html.PasswordFor(m => m.Password)
@* 客户端数据验证 *@
@Html.ValidationMessageFor(m => m.Password)
</td>
</tr>
<tr>
<td><input type="submit" value="提交" /></td>
</tr>
</table>
</form>
</body>
</html>
在控制器里面也添加校验
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class TestController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult PostData(UserInfo userInfo)
{
// 服务端数据验证
if (ModelState.IsValid)
{
return Content("数据有效");
}
return Content("数据无效");
}
}
}