asp.net core的输入模型验证

数据验证特性
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; }
  }
}

在控制器里面也添加校验

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("数据无效");
    }
  }
}

asp.net core的输入模型验证