zoukankan      html  css  js  c++  java
  • 在.Net MVC中自定义ValidationAttribute标签对Model中的属性做验证

    写一个继承与ValidationAttribute类的自定义的验证方法

    MVC中传递数据时,大多数都会用Model承载数据,并且在传到控制器后,对Model进行一系列的验证

    我平时经常使用的判断方法比Low,因为Model都是不同的,也需要返回很多不同的信息,所以我都是把很多条件语句封装成私有方法,放在控制器的最下边,然后使用的时候直接调用。

    下图就是我平时使用的代码格式,我把验证方法都写在了这里,很低级请轻喷。

    其实在.Net MVC中,已经提供了很好的验证方法,就是在属性上面加ValidationAttribute标签的方法,如下图:

    如果想要自定义验证的话就需要自己重写一下,下面是我写的简单自定义的验证方法

    方法功能是对字符串形式的属性长度的验证。方法如下

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    using System.ComponentModel.DataAnnotations;
    
    namespace WebTest.Common.Utility
    {
        public class ValidateStrLengthAttribute : ValidationAttribute
        {
            public ValidateStrLengthAttribute(int minLength, int maxLength) 
            {
                _minLength = minLength;
                _maxLength = maxLength;
            }
    
            /// <summary>
            /// 最小值
            /// </summary>
            private int _minLength = 0;
    
            /// <summary>
            /// 最大值
            /// </summary>
            private int _maxLength = 20;
    
            /// <summary>
            /// 重写验证规则
            /// </summary>
            /// <param name="value">model中此属性的值(这里是登录密码的值)</param>
            /// <param name="validationContext"></param>
            /// <returns></returns>
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                string name = validationContext.DisplayName;//属性名称
                string errorMessage = "";//错误信息
    
                if (value == null)
                {
                    errorMessage = " " + name + "不能为空";
                }
                else 
                {
                    string val = value.ToString();
    
                    if (string.IsNullOrEmpty(val))
                    {
                        errorMessage = " " + name + "不能为空";
                    }
                    else
                    {
                        if (val.Length >= _minLength && val.Length <= _maxLength)
                        {
                            return ValidationResult.Success;
                        }
                        else
                        {
                            errorMessage = " " + name + " 长度需在" + _minLength + "" + _maxLength + "之间";
                        }
                    }
                }
                return new ValidationResult(errorMessage);
            }
    
        }
    }

    下面我写一个小例子验证我的方法是否可用
    登录为例。

    Model代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    using System.ComponentModel.DataAnnotations;
    
    namespace WebTest.Models
    {
        public class LoginModel
        {
            /// <summary>
            /// 用户名
            /// </summary>
            [Display(Name = "用户名")]
            public string UserName { get; set; }
    
            /// <summary>
            /// 密码
            /// </summary>
            [Display(Name = "密码")]
            public string Pwd { get; set; }
        }
    }
    View Code

    控制器代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    using WebTest.Models;
    
    namespace WebTest.Controllers
    {
        public class LoginController : Controller
        {
            
            public ActionResult Index()
            {
                return View();
            }
    
            /// <summary>
            /// 登录表单提交
            /// </summary>
            /// <param name="model"></param>
            /// <returns></returns>
            [HttpPost]
            public ActionResult Index(LoginModel model)
            {
                return View();
            }
        }
    }
    View Code

    视图页代码:

    @model WebTest.Models.LoginModel
    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
    </head>
    <body>
        <div>    
            @using (@Html.BeginForm()) 
            { 
                @Html.LabelFor(model => model.UserName)
                @Html.TextBoxFor(model => model.UserName)
                @Html.ValidationMessageFor(model => model.UserName)
                <br />
                @Html.LabelFor(model => model.Pwd)
                @Html.TextBoxFor(model => model.Pwd)
                @Html.ValidationMessageFor(model => model.Pwd)
                <div>
                    <input type="submit" value="提交" />
                </div>
            }
        </div>
    </body>
    </html>
    View Code

    最后出来的页面是这样子的(普通的form表单)

    现在我可以把我的标签放到属性的上边方法名是ValidateStrLengthAttribute  标签名称是ValidateStrLength)需要引用下自定义验证方法的命名空间

    如下图:

    代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    using System.ComponentModel.DataAnnotations;
    using WebTest.Common.Utility;
    
    namespace WebTest.Models
    {
        public class LoginModel
        {
            /// <summary>
            /// 用户名
            /// </summary>
            [Display(Name = "用户名")]
            [ValidateStrLength(1, 9)]
            public string UserName { get; set; }
    
            /// <summary>
            /// 密码
            /// </summary>
            [Display(Name = "密码")]
            [ValidateStrLength(1, 9)]
            public string Pwd { get; set; }
        }
    }
    View Code

    现在都写完了,点击提交试一下

    例子完毕,如有问题,请多指正^_^。

  • 相关阅读:
    java基础学习总结——面向对象1
    java基础学习总结——基础语法2
    java基础学习总结——基础语法1
    java基础学习总结——开篇
    java基础学习总结——java环境变量配置
    Java基础加强总结(二)——泛型
    Java基础加强总结(一)——注解(Annotation)
    Web开发中设置快捷键来增强用户体验
    SQLServer2005中的CTE递归查询得到一棵树
    Jquery操作table
  • 原文地址:https://www.cnblogs.com/yinq/p/6074184.html
Copyright © 2011-2022 走看看