1

I have a self validation model in my code based on this link: ASP.NET MVC: Custom Validation by DataAnnotation

public class TestModel : IValidatableObject
{
    public string Title { get; set; }
    public string Description { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Title == null)
            yield return new ValidationResult("The title is mandatory.", new [] { "Title" });

        if (Description == null)
            yield return new ValidationResult("The description is mandatory.", new [] { "Description" });
    }
}

All of this works well. But my question is this: The error messages above are displayed as ValidationSummary errors. Is there any way to make the title error message display beside the title field (on the form view) and the description error message display beside the description field, just like in client side validation?

Community
  • 1
  • 1
Dan
  • 63
  • 2
  • 9

2 Answers2

1

First make sure that you have added the correct razor markup next to each field, for example:

@Html.ValidationMesageFor(m => m.Title)

This will display the error message only if there is an error in the ModelState that is associated with the same field, so ensure ModelState["Title"] contains the error, otherwise you won't see the message.

elolos
  • 4,310
  • 2
  • 28
  • 40
-1

This all is customized, at least, by CSS, or you can always use javascript (jquery).

UPDATE:

Well, i think, this is quite little info, therefore, try to add a some more.Basically, you also can use html.helper ValidationMessageFor + span tag. For instance:

@Html.EditorFor(x=>x.ModelProperty)<span>@Html.ValidationMessageFor(x=>x.ModelProperty)</span>

And in action method after your magic object validates itself, analyze result of your validation.
Just raugh demo:

var result = myObject.Validate(someContext);  
if (result != result.Success)
{ 
  ModelState.AddModelError("Title"); // if error in Title prop (otherwise "Description") 
  return View (myObject);
}

Or, if your model is validated through ValidationAttribute, you can check out this via ModelState.IsValid or ModelState.IsValidField methods.

Ryan
  • 609
  • 6
  • 13