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; }
    }
}

新建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("数据无效");
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值