Fork me on GitHub

李可

导航

统计

ASP.NET MVC4系列验证机制、伙伴类共享源数据信息(数据注解和验证)

回到顶部

一,mvc前后台验证

回到顶部

自定义属性标签MyRegularExpression

复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MvcAjaxValidate.Models
{
    public class MyRegularExpression:RegularExpressionAttribute
    {
        //为了多次修改正则,我们直接写一个类,只改这个地方就好//勿忘global文件
        //DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRegularExpression), typeof(RegularExpressionAttributeAdapter));

        public MyRegularExpression() : base(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$") { }
    }
}
复制代码
回到顶部

要起作用,需要在global文件注册适配器

     DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRegularExpression), typeof(RegularExpressionAttributeAdapter));

 

回到顶部

自定义model:

复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcAjaxValidate.Models
{
    public class DemoEntity
    {
        [Required(ErrorMessage = "*必填")]
        public int id { get; set; }

        [StringLength(10, ErrorMessage = "*长度小于10")]
        //[RegularExpression(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "必须邮箱")]
        [MyRegularExpression(ErrorMessage = "必须邮箱")]
        public string name { get; set; }

       // [Range(5, 10,ErrorMessage="5-10")]//数值,而不是长度
        
        [StringLength(5,ErrorMessage="最大5个字符")]
        //[MinLength(2,ErrorMessage="最小2个字符")]//不起作用,改成正则形式
        [RegularExpression(@"^.{2,}", ErrorMessage = "最小2个字符")]
        [DataType(DataType.Password)]
        public string password { get; set; }

        [DataType(DataType.Password)]
        [Compare("password", ErrorMessage = "密码要一致")]
        public string passwordRe { get; set; }
    }
}
复制代码
回到顶部

controller action

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcAjaxValidate.Models;

namespace MvcAjaxValidate.Controllers
{
    public class DemoEntityController : Controller
    {
        //
        // GET: /DemoEntity/

        public ActionResult create(DemoEntity demo)
        {
            if (ModelState.IsValid)
            {
                
            }
            return View();
        }

    }
}
复制代码
回到顶部

view(create强类型视图)

复制代码
@model MvcAjaxValidate.Models.DemoEntity

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>create</title>
</head>
<body>
    <script src="~/Scripts/jquery-1.7.1.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script>    
        function complete() {
            alert(1)
        }

    </script>
    @using (Ajax.BeginForm("create", new AjaxOptions() {HttpMethod="post", Confirm="ok?" , OnComplete="complete"}))
    {
        @Html.ValidationSummary(true)
    
        <fieldset>
            <legend>DemoEntity</legend>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.name)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.name)
                @Html.ValidationMessageFor(model => model.name)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.password)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.password)
                @Html.ValidationMessageFor(model => model.password)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.passwordRe)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.passwordRe)
                @Html.ValidationMessageFor(model => model.passwordRe)
            </div>
    
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>
复制代码
回到顶部

二,常为ef自动生成实体类采用伙伴类的技术验证

复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;//...
using System.Linq;
using System.Web;

namespace MvcAjaxValidate.Models
{   //伙伴类的技术,共享源数据信息
    //防止ef实体修改后,标签出被冲掉,我们换一个地方写。ef变 标签写到外面了,就不会丢了
    //让实体类和目标类共享信息,在这个类的所有属性,目标类就会有
    //这个类和目标类属性名一样哦
    //实体类和目标类要在一个命名空间!!!!!!!!!!!!!!!!
    [MetadataType(typeof(MetaTypeShare))]
    public partial class UserInfor
    {

    }
    //目标类
    public class MetaTypeShare
    {
        public int ID { get; set; }
        [Required(ErrorMessage="必填")]
        public string UName { get; set; }
        public string UPassword { get; set; }
        public Nullable<System.DateTime> USubTime { get; set; }
        public Nullable<System.DateTime> ULastMoltifyTime { get; set; }
        public Nullable<System.DateTime> ULastLoginTime { get; set; }
        public string UEmail { get; set; }
        public string UAddress { get; set; }
        public string UPhone { get; set; }
        public string URemark { get; set; }
        public Nullable<short> Usex { get; set; }
        public Nullable<short> UDelFlag { get; set; }
        public Nullable<int> UErrorCount { get; set; }
    }
    
}
复制代码

 

posted on   李可在江湖  阅读(478)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示