[Asp.Net MVC]自定义Metadata验证特性

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/david_520042/article/details/94380276

常用的验证特性标签: StringLength , Required , RegularExpression , Range , MembershipPasswordAttribute(密码强度限制)
也可以通过简单扩展, 增加自己的验证特性

/// <summary>
    /// 这东西也就是练手玩一下, 实际 .net framework已有  EmailAddressAttribute -> DataTypeAttribute -> ValidationAttribute
    /// </summary>
    public class EmailAttribute: RegularExpressionAttribute
    {
        public EmailAttribute()
            : base(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9] {1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4})$") //|[0-9]{1,3})(\)?]
        {
          
        }
    }

    public class UserBaseInfomation
    {
        /// <summary>
        /// 
        /// </summary>
        [Email(ErrorMessage="请输入有效的Email内容.")]
        public string Email { get; set; }

        [Range(0,9, ErrorMessage="用户类型的有效范围0-9")]
        public int UserType { get; set; }

    }
展开阅读全文

asp.net mvc 怎么进行验证的?

07-15

public partial class Dinner //验证类rn rn public bool IsValidrn rn get return (GetRuleViolations().Count() == 0); rn rn public IEnumerable GetRuleViolations()rn rn if (String.IsNullOrEmpty(Title))rn yield return new RuleViolation("Title required", "Title");rn if (String.IsNullOrEmpty(Description))rn yield return new RuleViolation("Description required", "Description");rn if (String.IsNullOrEmpty(HostedBy))rn yield return new RuleViolation("HostedBy required", "HostedBy");rn if (String.IsNullOrEmpty(Address))rn yield return new RuleViolation("Address required", "Address");rn if (String.IsNullOrEmpty(Country))rn yield return new RuleViolation("Country required", "Country");rn if (String.IsNullOrEmpty(ContactPhone))rn yield return new RuleViolation("Phone# required", "ContactPhone");rn if (!PhoneValidator.IsValidNumber(ContactPhone, Country))rn yield return new RuleViolation("Phone# does not match country",rn "ContactPhone");rn yield break;rn rn partial void OnValidate(ChangeAction action)rn rn if (!IsValid)rn throw new ApplicationException("Rule violations prevent saving");rn rnrnrn rnrnrn public class RuleViolationrn rn public string ErrorMessage get; private set; rn public string PropertyName get; private set; rn public RuleViolation(string errorMessage)rn rn ErrorMessage = errorMessage;rn rn public RuleViolation(string errorMessage, string propertyName)rn rn ErrorMessage = errorMessage;rn PropertyName = propertyName;rn rn rn public class PhoneValidatorrn rn static IDictionary countryRegex =rn new Dictionary() rn "USA", new Regex("^[2-9]\\d2-\\d3-\\d4$"),rn "UK", new Regex("(^1300\\d6$)|(^1800|1900|1902\\d6$)|(^0[2|3|7|8]1[0-9]8$)|(^13\\d4$)|(^04\\d2,3\\d6$)"),rn "Netherlands", new Regex("(^\\+[0-9]2|^\\+[0-9]2\\(0\\)|^\\(\\+[0-9]2\\)\\(0\\)|^00[0-9]2|^0)([0-9]9$|[0-9\\-\\s]10$)"),rn "中国", new Regex("[1-9][0-9]*")rn ;rnrn public static bool IsValidNumber(string phoneNumber, string country)rn rn if (country != null && countryRegex.ContainsKey(country))rn return countryRegex[country].IsMatch(phoneNumber);rn elsern return false;rn rnrn public static IEnumerable Countriesrn rn getrn rn return countryRegex.Keys;rn rn rn rnrnrnrn [AcceptVerbs(HttpVerbs.Post)] //更新方法rn public ActionResult Edit(int id, FormCollection formValues)rn rn var dinner = dinnerRepository.GetDinner(id);rn tryrn rn UpdateModel(dinner);rn dinnerRepository.Save();rn return RedirectToAction("Details", new id = dinner.DinnerID );rn rn catch (Exception)rn rn foreach (var issue in dinner.GetRuleViolations())rn rn ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);rn rn return View(dinner);rn rnrn rnrn//页面代码rn<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>rnrnrn Editrnrnrnrnrn Editrnrn <%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>rnrn <% using (Html.BeginForm()) %>rnrn rn Fieldsrn rn rn Title:rn <%= Html.TextBox("Title", Model.Title) %>rn <%= Html.ValidationMessage("Title", "*") %>rn rn rn EventDate:rn <%= Html.TextBox("EventDate", String.Format("0:g", Model.EventDate)) %>rn <%= Html.ValidationMessage("EventDate", "*") %>rn rn rn Description:rn <%= Html.TextBox("Description", Model.Description) %>rn <%= Html.ValidationMessage("Description", "*") %>rn rn rn HostedBy:rn <%= Html.TextBox("HostedBy", Model.HostedBy) %>rn <%= Html.ValidationMessage("HostedBy", "*") %>rn rn rn ContactPhone:rn <%= Html.TextBox("ContactPhone", Model.ContactPhone) %>rn <%= Html.ValidationMessage("ContactPhone", "*") %>rn rn rn Address:rn <%= Html.TextBox("Address", Model.Address) %>rn <%= Html.ValidationMessage("Address", "*") %>rn rn rn Country:rn <%= Html.TextBox("Country", Model.Country) %>rn <%= Html.ValidationMessage("Country", "*") %>rn rnrn rn rn rn rnrn <% %>rnrn rn <%=Html.ActionLink("Back to List", "Index") %>rn rnrnrnrn 怎么调用验证规则的啊 救命啊 论坛

没有更多推荐了,返回首页