2

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.

MeanGreen
  • 3,098
  • 5
  • 37
  • 63
Sandy
  • 2,429
  • 7
  • 33
  • 63

1 Answers1

1

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.

ediblecode
  • 11,701
  • 19
  • 68
  • 116
  • I clearly mentioned how this can be achieved in view. I know i can use regular expression in model. But i want this logic to be happen inside view, something like I tried. This is because I pass decimal position from controller action. For different currencies, it will be different. SO i cant hard code `{0,2}` in model. – Sandy Jul 09 '15 at 10:45
  • 2
    @Sandy Actually no you asked **how** it could be achieved in the view. I offered an alternative solution. It wasn't clear in your question that you wanted to do it on a per currency basis. – ediblecode Jul 09 '15 at 11:11
  • @Sandy See my edit for a more appropriate solution in your case. – ediblecode Jul 09 '15 at 11:23
  • will this support MVC3? – Sandy Jul 09 '15 at 12:38
  • @Sandy I would have thought so – ediblecode Jul 09 '15 at 12:39