2

Is there are a way to utilize Html.ValidationMessageFor() to return the validation text without the HTML markup around it?

Currently this code:

@Html.ValidationMessageFor(m => m.SomeProperty)

Returns this:

<span class="field-validation-error" data-valmsg-for="Model.SomeProperty" data-valmsg-replace="true">This field is required.</span>

And I would much prefer this:

This field is required.
2

2 Answers 2

2

m0s's comment pointed me to this StackOverflow question/answer. (How do I get the collection of Model State Errors in ASP.NET MVC?)

This is probably redundant but here is my working solution:

@if (ViewData.ModelState.ContainsKey("SomeProperty))
{
     @Html.TextBoxFor(m => m.SomeProperty), 
          new {
               @some_attribute = ViewData.ModelState["SomeProperty"].Errors[0].ErrorMessage })     
}

Obviously, you want to ensure your ModelState has errors before addressing the first one, in my case this will always be true.

Sign up to request clarification or add additional context in comments.

Comments

0

Try: htmlHelper.ValidationMessage(string ModelName). I think that returns the string without the markup.

2 Comments

Unfortunately that returns the same result.
Only other thing I can suggest is a custom template to display the error message and strip the unwanted html away inside the template.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.