MVC之模型验证----在模型类(Model Class)定义验证规则

模型验证是确保应用程序所接收的数据适合于绑定到模型,并且在不合适时给用户提供有用的信息。(实际就是当用户输入的数据不能验证和使用,要给出一些提示信息)
今天主要介绍,在模型类(Model Class)定义验证规则:将注解属性运用到模型类属性

案例:
用户注册时,其输入的信息,如账号、密码、身份证号码、年龄等等都有一定的验证规则,当然我们可以使用前端技术进行校验,其实从理论上讲,即使前端写了校验,但也可能存在提交到后台服务器端的数据有问题,那么就需要在服务端进行
二次验证,用来保证数据的完整性。

用元数据指定验证规则
MVC框架也至此用元数据来表达模型验证规则。使用元数据的优点:
在整个应用程序中运用过绑定过程的任何地方,都会强制执行验证规则。

内建的验证注解属性:
在这里插入图片描述
其对应的是.NET 类库中的位于
System.ComponentModel.DataAnnotations
命名空间下的注解属性类。
还有一个命名空间System.ComponentModel也提供了很多属性类用来支持以元数据的方式添加进行处理。

1.新建MVC项目:

1-1 准备实体类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace MVC_Project06.Models
{
    public class User
    {
        [DisplayName("用户编号")]
        public int UserId { get; set; }

        [DisplayName("账号")]
        //[RegularExpression(@"/^[a-zA-Z]\w{3,15}$/",ErrorMessage ="您输入的账号格式不正确!")]
        [Required]
        public string Account { get; set; }

        [DisplayName("密码")]
        [Required(ErrorMessage = "{0}不能为空")]
        [StringLength(12,MinimumLength =6,ErrorMessage ="{0}长度为{2}-{1}位")]
        //[RegularExpression("/^[a-zA-Z0-9_-]{6,16}$/",ErrorMessage ="您输入的密码格式不正确!")]
        public string Password { get; set; }

        [DisplayName("确认密码")]
        [Required(ErrorMessage = "{0}不能为空")]
        [StringLength(12, MinimumLength = 6, ErrorMessage = "{0}长度为{2}-{1}位")]
        //[RegularExpression("/^[a-zA-Z0-9_-]{6,16}$/", ErrorMessage = "您输入的密码格式不正确!")]
        [Compare("Password",ErrorMessage ="两次输入密码不一致!")]
        public string ConfirmedPassword { get; set; }

        [DisplayName("邮箱")]
        //[Required(ErrorMessage = "Please enter your email")]
        [EmailAddress(ErrorMessage ="您的邮箱格式输入不正确!")]
        public string Email { get; set; }

        [DisplayName("年龄")]
        [Range(1, 120, ErrorMessage = "Please enter your data between 1 and 120")]
        public int Age { get; set; }

        [DisplayName("电话号码")]
        [Phone(ErrorMessage ="您输入的电话号码格式有误!")]
        public string Telephone { get; set; }
    }
}

1-2 添加User控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_Project06.Models;

namespace MVC_Project06.Controllers
{
    public class UserController : Controller
    {
        // GET: User
        public ActionResult Register(User user)
        {
            if (ModelState.IsValid)
            {
                return View("Login");
            }

            //自定义验证
            ModelState.AddModelError("CustomError","you are wrong!");
            return View();
        }

        public ActionResult Login(User user)
        {            
            return View();
        }

        public ActionResult Success()
        {
            return View();
        }
    }
}

我们在实体类属性添加了注解验证规则,要么后台又该如何Check是否用户的输入都通过了验证?

Controller类中提供了属性:ModelState 返回一个模型绑定字典对象ModelStateDictionary,其IsValid属性用来检测模型绑定校验是否全部校验通过,返回bool值,返回值为true,则校验全部通过,否则校验失败。

1-3 添加Register动作方法对应的View视图:

@model MVC_Project06.Models.User
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>用户注册页面</title>
    <style>
        .text-danger {
            color:red;
        }
    </style>
</head>
<body>
    <div>
        @using (Html.BeginForm("Register", "User", FormMethod.Post, new { @id = "registerform" }))
        {

            <div class="dataElement">
                <label>@Html.DisplayNameFor(model => model.Account)</label>
                @Html.TextBoxFor(model => model.Account)
                @Html.ValidationMessageFor(model=>model.Account,"",new { @class = "text-danger" })

            </div>
            <div class="dataElement">
                <label>@Html.DisplayNameFor(model => model.Password)</label>
                @Html.PasswordFor(model => model.Password)
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })

            </div>

            <div class="dataElement">
                <label>@Html.DisplayNameFor(model => model.ConfirmedPassword)</label>
                @Html.PasswordFor(model => model.ConfirmedPassword)
                @Html.ValidationMessageFor(model => model.ConfirmedPassword, "", new { @class = "text-danger" })
            </div>

            <div class="dataElement">
                <label>@Html.DisplayNameFor(model => model.Age)</label>
                @Html.TextBoxFor(model => model.Age)
                @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
            </div>

            <div class="dataElement">
                <label>@Html.DisplayNameFor(model => model.Telephone)</label>
                @Html.TextBoxFor(model => model.Telephone)
                @Html.ValidationMessageFor(model => model.Telephone, "", new { @class = "text-danger" })
            </div>
            <div class="dataElement">
                <label>@Html.DisplayNameFor(model => model.Email)</label>
                @Html.TextBoxFor(model => model.Email)
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>

            //使用自定义验证
            @Html.ValidationMessage("CustomError")<br />
            <input type="submit" id="submitBtn" value="Submit" />
        }
    </div>
</body>
</html>

测试案例:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值