I've created a custom validation attribute to apply to my view model. In my form, I have a @Html.ValidationSummary
control. When my custom validation attribute is invalid, the summary control doesn't display the error message for some reason.
Here's my custom validator:
public class UserFolderExistsAttribute : ValidationAttribute
{
private const string _defaultErrorMessage =
"A folder with this name already exists";
private readonly object _typeId = new object();
public UserFolderExistsAttribute(string folderName) :
base(_defaultErrorMessage)
{
FolderName = folderName;
}
public string FolderName { get; private set; }
public override object TypeId { get { return _typeId; } }
public override bool IsValid(object value)
{
return false; // return error message to test for now
}
}
Here's my view model, with my custom validator attribute applied:
[UserFolderExists("Name")]
public class UserFolderViewModel
{
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
}
Here's my partial view:
@using (Ajax.BeginForm("Create", "Folders",
new AjaxOptions { OnSuccess = "OnSuccess" }))
{
@Html.AntiForgeryToken()
@Html.TextBoxFor(m => m.Name, new { placeholder = "Name" })
<p>@Html.ValidationSummary()</p>
<p><input type="submit" class="create" value="" /></p>
}
Here's the method my form is posting to:
[HttpPost]
public JsonResult Create(UserFolderViewModel viewModel)
{
if (ModelState.IsValid)
{
// do something
}
return Json("error");
}
The ModelState.IsValid
attribute returns false, so it recognizes my custom validator. But the summary control doesn't automatically display my message. The summary does recognize the Required
data annotation validator, and displays the error message.
How can I get the Validation Summary to display my custom error message?