Ng-pattern matching with UIMask



我的表单上有两个简单的inputs。 我需要它们匹配,但由于它们是电话号码,我为它们添加了一个uimask,以便用户只能输入数字,并且它会自动格式化为(999)-999-9999.

我的问题是,我所有确保这两个字段相互匹配的尝试都是错误的。 如果我使用uimask,我永远无法让它们匹配(从模型的角度来看(。 如果我从表单中删除uimask,则匹配将按预期工作。

请查看此代码笔以查看出现的问题。 我错过了什么吗? 还是我根本不允许模式匹配两个使用uimask的字段?

这是一个缩短的示例,以防代码笔不起作用。 我总是看到doesnt match的错误消息,即使这两个字段中的值相同。

<form name="demo" class="container"> 
<input class="form-control" type="text" 
id="phone" 
name="phone" 
ng-model="x"
ui-mask="(999) 999-9999" />
<input class="form-control" type="text" 
id="phone2" 
name="phone2" 
ng-model="y" 
ui-mask="(999) 999-9999" 
ng-pattern="(x)"/>
<div ng-messages="demo.phone2.$error" role="alert">
<div class="text-danger" ng-message="pattern">doesnt match.</div>
</div>

你误解了ng-pattern是如何工作的。ng-pattern是一个正则表达式验证器,ui-mask已经解决了很小的范围。 在您的示例中,第二个输入实际上是希望匹配正则表达式/^(x)$/,这将匹配文字字符串"x",而不是其中包含的变量。

如果要验证两个输入是否匹配,则必须添加自己的验证。 执行此操作的一种简单方法是添加ng-change事件以使用$setValidity(validationErrorKey, isValid)手动操作表单元素的有效性。 我个人会把这种放在你的表单的控制器中,但这些对代码笔中代码的调整应该可以工作。

<input class="form-control" ng-class="{requiredControl:demo.phone.$dirty && demo.phone.$invalid}" type="text" 
id="phone" 
name="phone" 
ng-model="x"
ng-change="demo.phone2.$setValidity('match', x==y)"
ng-required="true"
ui-options="{clearOnBlur:false}" ui-mask-placeholder 
ui-mask-placeholder-char="_" 
ui-mask="(999) 999-9999" />    
<input class="form-control" ng-class="{requiredControl:demo.phone.$dirty && demo.phone.$invalid}" type="text" 
id="phone2" 
name="phone2" 
ng-model="y" 
ng-required="true"
ng-change="demo.phone2.$setValidity('match', x==y)"
ui-options="{clearOnBlur:false}" ui-mask-placeholder 
ui-mask-placeholder-char="_" 
ui-mask="(999) 999-9999"/>

然后,只需确保在ng-messages中引用正确的错误标签即可。 我使用了一个标记为'match'的新错误而不是内置'pattern'来更好地传达验证的用途。

<div ng-messages="demo.phone.$error" role="alert" ng-if="demo.phone.$dirty">
<div class="text-danger" ng-message="match">doesnt match.</div>
</div>

代码笔的分支

最新更新