允许在文本框中输入不带前导零的内容

发布于 2024-12-10 07:06:18 字数 359 浏览 0 评论 0原文

我有一个 ASP.NET Web 应用程序,我的视图模型有一个双字段 PowerPrice,但如果用户不输入前导零,则该字段的验证将关闭。验证会显示“请输入一个数字”。如何允许用户输入“.11”而不是要求“0.11”?这是我的视图和模型代码:

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

public double PowerPrice
{
    get;
    set;
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一江春梦 2024-12-17 07:06:18

您正在为 Double 类型的对象设置一个类型不正确的值(在本例中为“.11”)。它总是会失败。

你有几个我能立即想到的选择。

或者,

  • 您可以按原样保留代码,然后在客户端上通过 JavaScript 或 JQuery 等客户端代码检测内容在那里,所以你说你只担心点像“.12”这样的东西,然后如果你检测到这种情况,根据你想要的添加一个前导零或数字。这将确保它到达服务器时它是一个十进制值并被接受,而无需在服务器端进行解析或更改。

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.
活雷疯 2024-12-17 07:06:18

我相信这个这里的答案指出了真正的罪魁祸首 - 1.10 之前的 jQuery.Validation 版本有一个验证正则表达式损坏。根据后面对答案的评论,只需将您的 jQuery.Validation 升级(例如 nuget)到最新版本即可。

就我而言,从 1.9.0.1 升级到 1.11.1 就成功了。根本不需要服务器端/模型绑定器/字符串 ViewModel 更改。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文