Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow text box entry without leading zero

I have an ASP.NET web application, my view model has a double field PowerPrice, but the validation for the field goes off if the user doesn't enter a leading zero. The validation will say "please enter a number." How can I allow the user to enter ".11" instead of requiring "0.11"? Here is my view and model code:

<div class="editor-field">
    @Html.EditorFor(model => model.PowerPrice)
    @Html.ValidationMessageFor(model => model.PowerPrice)
</div>

public double PowerPrice
{
    get;
    set;
}
like image 432
Joshua Smith Avatar asked Feb 25 '26 06:02

Joshua Smith


1 Answers

You are setting a value that is not of the right type in this case ".11" to an object of type Double. It will always fail.

You have a couple of options that I can think of off the top of my head.

  • Change the type of the Double to String and once you get it try to parse it to what you want. Also on the interface to reduce what garbagge can be entered use a regex validator or custom validator or use a AjaxControlToolkit MaskEditor (see http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/MaskedEdit/MaskedEdit.aspx)

Or,

  • You could keep your code as is and then on the client via client side code like JavaScript or JQuery detect whats there, so you said you're only worried about dot some thing like ".12", then if you detect that scenario add a leading zero or number depending on what you want to it. This will ensure on it reaching the server its a decimal value and accepted without parsing or changing on the server side.
like image 126
Pasha Immortals Avatar answered Feb 28 '26 16:02

Pasha Immortals



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!