Reputation: 2449
I have a requirement like @Html.TextBoxFor
to show the currency in a comma seperated format, without accepting negative values and without special characters. At the same time when the currency is not available, I'm changing the value of this TextBoxFor to 'not available'. How this can be achieved in the View, using decimal validation and supporting text input?
@Html.TextBoxFor(m => m.SourceCurrencyValue, new { @Value=String.Format("{ViewBag.decimalplace}",Model.SourceCurrencyValue) })
ViewBag.decimalplace
should be the decimal position like 2 or 3.
Upvotes: 2
Views: 5804
Reputation: 11971
You could use a RegularExpression
- this one will limit the number of decimal places to 2, but change accordingly.
[RegularExpression(@"^\d+,\d{0,2}$",
ErrorMessage = "Your error message")]
public decimal SourceCurrencyValue { get; set; }
After seeing your comment for clarification, you can use the idea above. The data attribute creates data attributes on the element when it's rendered, if you want to do this on a per view basis, why not try setting those attributes manually:
@{ var regex = string.Format(@"^\d+,\d{{0,{0}}}$", ViewBag.DecimalPlaces); }
@Html.TextBoxFor(model => model.SourceCurrencyValue,
new { data_val_regex_pattern = regex, data_val_regex = "Error message" })
This will then change the number of decimal places based on how many you pass in.
Upvotes: 1