允许在文本框中输入不带前导零的内容
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在为 Double 类型的对象设置一个类型不正确的值(在本例中为“.11”)。它总是会失败。
你有几个我能立即想到的选择。
将其解析为您想要的内容。还可以在界面上减少什么
可以使用正则表达式验证器或自定义验证器输入垃圾,或者
使用 AjaxControlToolkit MaskEditor(请参阅
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/MaskedEdit/MaskedEdit.aspx )
或者,
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.
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,
我相信这个这里的答案指出了真正的罪魁祸首 - 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
) yourjQuery.Validation
to the latest version.In my case, upgrading from
1.9.0.1
to1.11.1
did the trick. There is no server side / Model binder / string ViewModel changes needed at all.