Joshua Smith
Joshua Smith

Reputation: 421

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;
}

Upvotes: 3

Views: 979

Answers (2)

StuartLC
StuartLC

Reputation: 107317

I believe this answer here pinpoints the actual culprit - jQuery.Validation versions prior to 1.10 have a broken validation regex. As per the later comments on the answer, simply upgrade (e.g. nuget) your jQuery.Validation to the latest version.

In my case, upgrading from 1.9.0.1 to 1.11.1 did the trick. There is no server side / Model binder / string ViewModel changes needed at all.

Upvotes: 0

Pasha Immortals
Pasha Immortals

Reputation: 839

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.

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.

Upvotes: 1

Related Questions