ValidationMessageFor只读属性,或者一个ValidationMessageFor两个属性

时间:2013-07-17 18:44:32

标签: c# asp.net-mvc forms validation

我有一个包含

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

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

当FirstName或LastName为空时,是否可能有Html.ValidationMessageFor FullName或某些自定义验证消息?

更新

这就是我想要的。

  1. 您将两个名称留空:Full name is required.
  2. 您将FirstName留空:Full name is required.
  3. 您将LastName留空:Full name is required.

1 个答案:

答案 0 :(得分:1)

你可以做以下事情(我希望我没有误会你):

[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)

我希望这会有所帮助。