Christian Phillips
Christian Phillips

Reputation: 18779

MVC RegularExpression Model Attribute Issue

I have a model, with a property and a ReqularExpression attribute that looks like this...

[RegularExpression(@"^[0-9]{2}\s[a-zA-Z]{3}$", ErrorMessage = "Invalid Facility {NN CCY}")]
public string Facility { get; set; }

The partial view then simply has a text box using the above property...

@Html.TextBoxFor(model => model.Facility, new { @class = "form-control",
                                       placeholder = "Should be NN CCY, example: 01 EUR" })
@Html.ValidationMessageFor(model => model.Facility)

The Yellow Screen of death is giving me this error:

[FormatException: Input string was not in a correct format.]
System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args) +14305394
System.String.Format(IFormatProvider provider, String format, Object[] args) +136
System.Web.Mvc.RegularExpressionAttributeAdapter.GetClientValidationRules() +64 System.Linq.d__142.MoveNext() +267 System.Web.Mvc.UnobtrusiveValidationAttributesGenerator.GetValidationAttributes(IEnumerable1 clientRules, IDictionary`2 results) +456
System.Web.Mvc.HtmlHelper.GetUnobtrusiveValidationAttributes(String name, ModelMetadata metadata) +280

The fiels isn't populated with anything but the placeholder, and I get this error which highlights the @Html.TextBoxForLine. Removing the attribute solves the problem, what am I missing here?

Upvotes: 0

Views: 269

Answers (1)

Christian Phillips
Christian Phillips

Reputation: 18779

I figured out the issue by some further investigation, and this article gave me a hint to the StringBuilder.AppendFormat where curly braces are used in the string. My ErrorMessage, "Invalid Facility {NN CCY}" contains curly braces, and I replaced these with parenthesis and it now works.

I'll leave this here for now in case others get a similar frustrating issue.

Upvotes: 2

Related Questions