Search code examples
javascriptjqueryasp.net-mvchtml.textboxfor

set textboxfor to accept 2 decimal places


I have these two textboxfor's and I need them to only allow input of 2 decimal places. I'm assumming a jQuery or Javascript event can do this. I am just not sure how to call the textboxfor's in the Javascript. Any help would be appreciated

@Html.TextBoxFor(m => Model.Categories[c].EstimateGroups[g].EstimateItems[i].PerUnitCost,
                 new { @disabled = "disabled", @onchange = "costUpdate(this);", @cstType = "perUnit",@id="perUnit"})

<span class="sideLabel">@Model.Categories[c].EstimateGroups[g].EstimateItems[i].PerUnitDescription</span>

if (Model.Categories[c].EstimateGroups[g].EstimateItems[i].Units != null
 && !Model.Categories[c].EstimateGroups[g].EstimateItems[i].IsBasedOnHomeSquareFootage)
{ 
    @Html.TextBoxFor(m => Model.Categories[c].EstimateGroups[g].EstimateItems[i].Units,
                     new { @disabled = "disabled", @onchange = "costUpdate(this);", @cstType = "units" })
}

Solution

  • You can use the RegularExpression attribute. This will do the job.

    [RegularExpression(@"^\d+.\d{0,2}$", 
                 ErrorMessage = "It cannot have more than one decimal point value")]
    public double PerUnitCost {get;set;}   
    

    Here In {0,2}, 0 and 2 means minimum and maximum digits after decimal place. So change according to you requirement.