using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace 注解的應用.Models
{
public class User
{
[HiddenInput(DisplayValue = false)]
//[ScaffoldColumn(false)]
[Display(Name="編號")]
public int Id { get; set; }
[Display(Name="用戶名")]
//[StringLength(10)]
//[Common.MyStringLength(10,ErrorMessage="{0}字數太多了!")]
//[Common.MyStringLength(5)]
[Common.MyStringLength(5,ErrorMessage="{0}字符太少了")]
[Required(ErrorMessage="請輸入用戶名")]
[Remote("CheckValid", "Home", AdditionalFields = "UserName,Pwd",ErrorMessage="該用戶已存在,請重新輸入")]
public string UserName { get; set; }
[DataType(DataType.Password)]
[Display(Name="密碼")]
[System.ComponentModel.DataAnnotations.Compare("UserName",ErrorMessage="密碼不一致")]
public string Pwd { get; set; }
[DisplayFormat(DataFormatString="{0:C}",ApplyFormatInEditMode=false)]
[Range(10,30)]
public decimal Price { get; set; }
//使用DataType(DataType.EmailAddress,ErrorMessage="請輸入正確的Email地址")自定義的錯誤消息不會生效
//[DataType(DataType.EmailAddress,ErrorMessage="請輸入正確的Email地址")]
[RegularExpression(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "請輸入正確的Email地址")]
public string Email { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace 注解的應用.Common
{
/// <summary>
/// 自定義注解類,自定義注解不支持客戶端驗證,在模型綁定時執行IsValid方法執行驗證邏輯,
/// 如果不調用FormatErrorMessage方法進行格式化,傳入格式化的錯誤消息,則在
/// [Common.MyStringLength(10,ErrorMessage="{0}字數太多了!")]中自定義的消息不回生效
/// </summary>
public class MyStringLengthAttribute:ValidationAttribute
{
private readonly int MaxLength;
public MyStringLengthAttribute(int maxLength)
{
this.MaxLength = maxLength;
}
//protected override ValidationResult IsValid(object value, ValidationContext validationContext)
//{
// string content = value.ToString();
// if (content.Length > MaxLength)
// {
// //return new ValidationResult("輸入的字符太多了!^_^");
// string errorMessage = FormatErrorMessage(validationContext.DisplayName);
// return new ValidationResult(errorMessage);
// }
// return ValidationResult.Success;
// //return base.IsValid(value, validationContext);
//}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
if (value.ToString().Length < MaxLength)
{
//return new ValidationResult("請輸入" + MaxLength + "位以上長度的字符!");
string errorMessage = FormatErrorMessage(validationContext.DisplayName + "請輸入" + MaxLength + "位以上長度的字符!");
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success;
}
}
}