Newline in a ValidationMessage

13.4k views Asked by At

I'm testing a list of things for null. Every time I find one, I save it in an array to implement it in a validationmessage.

Output I want looks like this:

Field 1 is required
Field 4 is required
etc...

But I can't seem to be able to start a new line.

Now, it looks like this:

Field 1 is required Field 4 is required

Does anybody know how to achieve this?

EDIT:

controller:

IDictionary<int, String> emptyFields = new Dictionary<int, String>();

foreach (Something thing in AnotherThing.Collection)
{
    if (thing.Property == null)
        emptyFields.add(thing.Index, thing.Name);                   
}

if (emptyFields.Any())
    throw new CustomException() { EmptyFields = emptyFields };

This exception is handled here:

catch (CustomException ex)
{                   
    ModelState.AddModelError("file", ex.GetExceptionString());
    return View("theView");
}    

CustomException:

public class CustomException: Exception
{
    public IDictionary<int,String> EmptyFields { get; set; }
    public override String Label { get { return "someLabel"; } }
    public override String GetExceptionString()
    {
        String msg = "";
        foreach (KeyValuePair<int,String> elem in EmptyFields)
        {
            msg += "row: " + (elem.Key + 1).ToString() + " column: " + elem.Value + "<br/>";      
        }
        return msg;        
    }
}

view:

<span style="color: #FF0000">@Html.Raw(Html.ValidationMessage("file").ToString())</span>
7

There are 7 answers

3
Leniel Maccaferri On BEST ANSWER

You can do it with this one liner:

@Html.Raw(HttpUtility.HtmlDecode(Html.ValidationMessageFor(m => m.Property).ToHtmlString()))
1
Shivkumar On

try this one

append
tag after each error message and use Html.Raw() method to display your content Html.Raw will decode HtmlContent.

you message like 
 Field 1 is required <br/>Field 4 is required<br/> 

In View

Html.Raw("Yore Error Message")
0
GraemeMiller On

Are you displaying them in a validation summary? I don’t think it supports html for line breaks etc. I'd create a custom html helper based on validation summary that displays html.

The same applies to validationmessage so probably need to make a custom helper for that

11
Darin Dimitrov On

You will need to write a custom helper to achieve that. The built-in ValidationMessageFor helper automatically HTML encodes the value. Here's an example:

public static class ValidationMessageExtensions
{
    public static IHtmlString MyValidationMessageFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper, 
        Expression<Func<TModel, TProperty>> ex
    )
    {
        var htmlAttributes = new RouteValueDictionary();
        string validationMessage = null;
        var expression = ExpressionHelper.GetExpressionText(ex);
        var modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);
        var formContext = htmlHelper.ViewContext.ClientValidationEnabled ? htmlHelper.ViewContext.FormContext : null;
        if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName) && formContext == null)
        {
            return null;
        }

        var modelState = htmlHelper.ViewData.ModelState[modelName];
        var modelErrors = (modelState == null) ? null : modelState.Errors;
        var modelError = (((modelErrors == null) || (modelErrors.Count == 0)) 
            ? null 
            : modelErrors.FirstOrDefault(m => !String.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0]);

        if (modelError == null && formContext == null)
        {
            return null;
        }

        var builder = new TagBuilder("span");
        builder.MergeAttributes(htmlAttributes);
        builder.AddCssClass((modelError != null) ? HtmlHelper.ValidationMessageCssClassName : HtmlHelper.ValidationMessageValidCssClassName);

        if (!String.IsNullOrEmpty(validationMessage))
        {
            builder.InnerHtml = validationMessage;
        }
        else if (modelError != null)
        {
            builder.InnerHtml = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, modelState);
        }

        if (formContext != null)
        {
            bool replaceValidationMessageContents = String.IsNullOrEmpty(validationMessage);
            builder.MergeAttribute("data-valmsg-for", modelName);
            builder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant());
        }

        return new HtmlString(builder.ToString(TagRenderMode.Normal));
    }

    private static string GetUserErrorMessageOrDefault(HttpContextBase httpContext, ModelError error, ModelState modelState)
    {
        if (!String.IsNullOrEmpty(error.ErrorMessage))
        {
            return error.ErrorMessage;
        }
        if (modelState == null)
        {
            return null;
        }

        var attemptedValue = (modelState.Value != null) ? modelState.Value.AttemptedValue : null;
        return string.Format(CultureInfo.CurrentCulture, "Value '{0}' not valid for property", attemptedValue);
    }
}

and then:

public class MyViewModel
{
    [Required(ErrorMessage = "Error Line1<br/>Error Line2")]
    public string SomeProperty { get; set; }
}

and in the view:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.SomeProperty)
    @Html.MyValidationMessageFor(x => x.SomeProperty)
    <button type="submit">OK</button>
}

And if you want to display the error message in a ValidationSummary you could also write a custom helper that will not HTML encode the error message as I have shown in this post.

0
s1cart3r On

Appreciated I am a bit late to this party, but just had this issue and using plain old css also works well:

<style>
    .field-validation-error::after {
        content: "\a";
        white-space: pre;
    }
</style>
0
CyberNinja On

what I do is bunch them in a div

       <div class="Errors">

        @Html.ValidationMessageFor(m => m.Name)<br/>
        @Html.ValidationMessageFor(m => m.LName)<br />
      </div>

then create a class

     .Errors {
          color: red;
          font-size: 10px;
          font-weight: bold;
          }

but if you wanna do a multiline error then what Leinel mentioned is the best way.the reason I bunch them is some users will not see the error with long forms and they'll just start calling us.. ^^,

0
camainc On

In case anyone is looking for it, here is how to do this for a validation summary:

@Html.Raw(HttpUtility.HtmlDecode(Html.ValidationSummary(true).ToHtmlString()))