簡體   English   中英

ValidationMessageFor只讀屬性,或一個ValidationMessageFor兩個屬性

[英]ValidationMessageFor readonly property, or one ValidationMessageFor two properties

我有一個包含

[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }

public string FullName {
    get {
        return this.FirstName + " " + this.LastName;
    }
}

是否有Html.ValidationMessageFor FullName或FirstName或LastName為空白時出現的某些自定義驗證消息?

UPDATE

這就是我要的。

  1. 請將兩個名稱都保留為空白: Full name is required.
  2. 您將名字留為空白:必須輸入Full name is required.
  3. 您將姓氏留空:必須輸入Full name is required.

您可以執行以下操作(我希望我不會誤會您):

[Required(ErrorMessage="Yo fill this up please"]
public string FirstName { get; set; }

編輯

如果您有一些更具體的驗證要求,則可以通過模型實現IValidateObject ,例如:

public class Person : IValidatableObject
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string FullName
    {
        get { return string.Format("{0} {1}", FirstName, LastName); }
    }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (string.IsNullOrEmpty(FirstName) || string.IsNullOrEmpty(LastName))
        {
            yield return new ValidationResult("The full name is required.");
        }
    }
}

然后在您的Controller中,ModelState將指示輸入是否無效:

[HttpPost]
public ActionResult Create(Person person)
{
    if (!ModelState.IsValid)
    {
        return View();
    }

    // do your stuff here ...
}

當然,在您看來,您可以通過ValidationSummary獲取驗證消息:

@Html.ValidationSummary(true)

我希望這有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM