2012-07-30 30 views
1

我有我的數據模型以下屬性:使用數據註釋,檢查是否有特定值

[Required] 
[DataType(DataType.Text)] 
[Display(Name = "First Name")] 
public string FirstName { get; set; } 

[Required] 
[DataType(DataType.Text)] 
[Display(Name = "Last Name")] 
public string LastName { get; set; } 

我的文本框,目前在他們的佔位符,這樣當他們專注於文本框中的放置區會消失在文本框內,如果他們沒有輸入任何東西然後文本框val($(textbox).val())等於「First Name」或「Last Name」,我該如何檢查這個錯誤會在我的驗證中返回如果FirstNameLastName等於「名字」和「姓氏」,說「請填寫名字/姓氏」

+0

重複/問題/ 6902187 /設定初始值換所需的屬性 – hatchet 2012-07-30 22:35:20

回答

5

你應該寫自己ValidationAttribute,並用它在你的屬性

簡單的例子:

public sealed class PlaceHolderAttribute:ValidationAttribute 
{ 
    private readonly string _placeholderValue; 

    public override bool IsValid(object value) 
    { 
     var stringValue = value.ToString(); 
     if (stringValue == _placeholderValue) 
     { 
      ErrorMessage = string.Format("Please fill out {0}", _placeholderValue); 
      return false; 
     } 
     return true; 
    } 

    public PlaceHolderAttribute(string placeholderValue) 
    { 
     _placeholderValue = placeholderValue; 
    } 
} 

使用它你的財產是這樣的:http://stackoverflow.com的

[Required] 
[DataType(DataType.Text)] 
[Display(Name = "First Name")] 
[PlaceHolder("First Name")] 
public string FirstName { get; set; } 
相關問題