我正在为电话号码使用jQuery Maskedinput plugin构建ASP.NET MVC 5应用程序。但是,该插件会导致长度验证程序触发。jQuery蒙面输入触发器验证
这里的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>
而这里的由上述剃刀代码生成的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的指导,我用这种方式写了面具和“unmask” d加入他们的_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验证方法。 –
我的要求是,它不包含在去db前的破折号 - 它只是数字。 – Alex
是的,它不会张贴短划线。它只是为了张贴。 –