Model验证功能

2018-06-22 06:42:28来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

占位符

 {0}对应属性
 {1}对应minimum
 {2}对应maximum
 
[StringLength(15, MinimumLength = 6, ErrorMessage = "密码长度必须在{2}和{1}之间")]
 
先创建一个资源文件
 
为了实现这种验证效果
 
资源文件里可以这样写
 
然后新建一个类,这个类主要实现验证和其它一些额外的属性,这个类是部分类,有加partial关键字,写注解别忘了加
System.ComponentModel.DataAnnotations命名空间
 
[MetadataType(typeof(Login_UserMetaData))]
    public partial class Login_User
    {
        //验证需要用到
        public class Login_UserMetaData
        {
            [Display(Name="用户名")]
            [Required(ErrorMessageResourceName="Required",ErrorMessageResourceType=typeof(Resource))]
            public string UserName { get; set; }
            [Display(Name="密码")]
            [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resource))]
            public string Password { get; set; }
        }
    }

 

然后控制器大概就需要这样的代码,记得action方法传进来的参数类型是类名,如果用string username这种形式,ModelState.IsValid将无效

[HttpPost]
        public ActionResult Login(Login_User loginUser)
        {
            if (!ModelState.IsValid)
            {//验证不通过返回
                return View();
            }
            Login_User user=userManager.Login(loginUser.UserName, loginUser.Password);
            if (user == null)
            {//用户密码错误!
                ViewBag.error = "用户名或密码错误!";
                return View();
            }
            Session["user"] = user;
            return RedirectToAction("index", "home");
        }

 

这样做了之后,就可以实现服务端验证了,但这样还不够,这里还需要使用客户端验证,这可以大大减轻服务器负担。
view中的代码如下:
@{
    ViewBag.Title = "后台登陆";
}
@model Letter.Data.Model.Login_User
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
@using(Html.BeginForm()){
    <div>  
        <label for="username">用户名:</label>  
        @Html.TextBoxFor(u=>u.UserName) @Html.ValidationMessage("UserName")  
    </div>  
    <div>  
        <label for="password">密码:</label>  
        @Html.PasswordFor(u=>u.Password) @Html.ValidationMessage("Password")
    </div>
    <div>
        <input type="submit" value="登录" />@ViewBag.error
    </div>
}

web.config应该有如下配置才有效

 

附上一个比较完整的验证

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

namespace RegisterValidation.Models
{
    
    public partial class User
    {
        [Key]
        public int ID { get; set; }
        [Display(Name="姓名")]
        [Required(ErrorMessageResourceName="Required",ErrorMessageResourceType=typeof(Resource))]
        public string Name { get; set; }

        [Display(Name="生日")]
        //[RegularExpression(@"^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$",ErrorMessageResourceName="Regular",ErrorMessageResourceType=typeof(Resource))]
        [Required(ErrorMessageResourceName="Required",ErrorMessageResourceType=typeof(Resource))]
        public DateTime? Birthday { get; set; }

        [Display(Name="年龄")]
        [Range(18,60,ErrorMessageResourceName="Range",ErrorMessageResourceType=typeof(Resource))]
        public int Age { get; set; }

        [Display(Name="用户名")]
        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resource))]
        public string Username { get; set; }

        [Display(Name="密码")]
        [Required(ErrorMessageResourceName="Required",ErrorMessageResourceType=typeof(Resource))]
        public string Password { get; set; }

        [Display(Name="邮箱")]
        [Required(ErrorMessageResourceName="Required",ErrorMessageResourceType=typeof(Resource))]
        [RegularExpression(@"^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$",ErrorMessageResourceName="Regular",ErrorMessageResourceType=typeof(Resource))]
        public string Email { get; set; }

    }
    public class UserDBContext : DbContext
    {
        public DbSet<User> Users { get; set; }
    }
}

另一个部分user类,包含确认密码

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

namespace RegisterValidation.Models
{
    public partial  class User
    {
        [Display(Name="确认密码")]
        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resource))]
        [StringLength(10,MinimumLength=5,ErrorMessageResourceName="StringLength",ErrorMessageResourceType=typeof(Resource))]
        [Compare("Password",ErrorMessageResourceName="Compare",ErrorMessageResourceType=typeof(Resource))]
        public string PasswordConfirm { get; set; }
    }
}

 

资源文件如下

效果如下

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:【.NET深呼吸】清理对象引用,有一个问题容易被忽略

下一篇:Cheatsheet: 2015 01.01~ 01.31