【发布时间】:2017-07-20 16:15:53
【问题描述】:
我正在构建一个 ASP.NET MVC 5 应用程序,使用 jQuery Maskedinput plugin 作为电话号码。但是,插件会触发长度验证器。
这是 C# 属性定义:
[StringLength(10)]
[DataType(DataType.PhoneNumber)]
public string Phone_Nbr { get; set; }
这是视图中的表单字段:
<div class="form-group-sm clearfix">
@Html.LabelFor(m => m.CustomerVm.Phone_Nbr,
htmlAttributes: new { @class = "control-label col-xs-5 col-md-5" })
<div class="col-xs-2 col-md-2">
@Html.EditorFor(m => m.CustomerVm.Phone_Nbr,
new { htmlAttributes = new { @class = "form-control phone" } })
@Html.ValidationMessageFor(m => m.CustomerVm.Phone_Nbr, "",
new { @class = "text-danger" })
</div>
</div>
以下是上述 Razor 代码生成的 HTML:
<div class="form-group-sm clearfix">
<label class="control-label col-xs-5 col-md-5" for="CustomerVm_Phone_Nbr">Phone #</label>
<div class="col-xs-2 col-md-2">
<input class="form-control phone text-box single-line input-validation-error"
data-val="true" data-val-length="The field Phone # must be a string with a maximum length of 10."
data-val-length-max="10" id="CustomerVm_Phone_Nbr" name="CustomerVm.Phone_Nbr"
type="tel" value="9103440700" aria-describedby="CustomerVm_Phone_Nbr-error"
aria-invalid="true">
<span class="text-danger field-validation-error" data-valmsg-for="CustomerVm.Phone_Nbr"
data-valmsg-replace="true">
<span id="CustomerVm_Phone_Nbr-error" class="">The field Phone # must be a string with a maximum length of 10.</span>
</span>
</div>
</div>
在this answer的指导下,我以这种方式编写了掩码和“取消掩码”,并将它们添加到_Layout.cshtml的文档准备功能中,因此所有视图都可以访问它们:
$('.phone')
.mask('999-999-9999')
.on('blur', function () {
var frm = $(this).parents("form");
// if form has a validator
if ($.data(frm[0], 'validator')) {
var validator = $(this).parents("form").validate();
validator.settings.onfocusout.apply(validator, [this]);
}
});
// Unmask the phone number on-submit of the form.
$('form').submit(function () {
$('.phone').each(function (index, element) {
var value = $(element).val().replace(/-/g, '');
$(element).val(value);
});
});
任何具有.phone 类的表单元素都将应用掩码。 blur 处理程序旨在防止在我们清除电话号码的必填字段时进行不必要的验证;请注意,此字段不是必需的,但要求的最大长度为 10。当我尝试提交时,我在客户端收到此验证错误:
我希望上面的“取消屏蔽”(在提交表单时会从 .phone 类的元素中删除所有破折号)可以防止这个问题。事实上,在值进入数据库之前,需要删除破折号,所以它只是纯数字。
我做错了什么?谢谢。
【问题讨论】:
-
您可以使用 jquery validate 方法进行验证。
-
我的要求是在去数据库之前它不包含破折号——它只是数字。
-
是的,它不会发布破折号。它只是发布而已。
标签: javascript jquery validation