Reputation: 5832
I have a decimal property in my VM:
[Required, Display(Name = "Manual Payment Amount")]
[DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
public decimal EnteredPaymentAmount { get; set; }
the View looks like this:
@Html.TextBoxFor(m => m.EnteredPaymentAmount, new { style = "width:200px", maxlength = Model.MaximumPaymentAmount.ToString("N").Length })
I want to limit the input to only have 2 decimal places
What is the best way of doing this? I tried to apply the DisplayFormat but also the format on the TextBoxFor but that still passed the validation meaning I can enter say 3 decimal places.
Upvotes: 0
Views: 1870
Reputation: 172618
How about this:-
@{var formated = String.Format("{0:0.00}", EnteredPaymentAmount);}
@Html.TextBoxFor(m => m.EnteredPaymentAmount, formated, new { id = "id"})
EDIT:-
You can try to use EditorFor
also
@Html.EditorFor(m => m.EnteredPaymentAmount)
Upvotes: 0
Reputation: 5832
$('input#EnteredPaymentAmount').blur(function () {
var num = parseFloat($(this).val());
var cleanNum = num.toFixed(2);
$(this).val(cleanNum);
});
I used the above code and it worked just fine.
Upvotes: 0
Reputation: 1039438
You could use some client side plugin that would allow you to define a regular expression for the allowed input. For example the jQuery maskedInput
plugin.
Upvotes: 1