forms – 在AngularJS中比较表单验证中的两个输入值
发布时间:2020-12-17 08:37:29 所属栏目:安全 来源:网络整理
导读:我试图做一个表单验证使用AngularJS。我特别感兴趣的比较两个值。我希望用户在继续之前确认他输入的一些数据。让我说我有下面的代码: p Email:input type="email" name="email1" ng-model="emailReg" Repeat Email:input type="email" name="email2" ng-mod
我试图做一个表单验证使用AngularJS。我特别感兴趣的比较两个值。我希望用户在继续之前确认他输入的一些数据。让我说我有下面的代码:
<p> Email:<input type="email" name="email1" ng-model="emailReg"> Repeat Email:<input type="email" name="email2" ng-model="emailReg2"> <p> 然后我可以使用验证: <span ng-show="registerForm.email1.$error.required">Required!</span> <span ng-show="registerForm.email1.$error.email">Not valid email!</span> <span ng-show="emailReg !== emailReg2">Emails have to match!</span> <-- see this line registerForm。$ valid将对输入中的文本做出正确的反应,除非我不知道如何在验证之前使用比较来强制电子邮件相同,然后才允许用户提交表单。 我想要有一个没有自定义指令的解决方案,但如果这不能实现没有它,我会处理它。 Here是一个解决类似问题与自定义指令的答案。 任何帮助赞赏,谢谢
实现这一点的一种方法是使用自定义指令。这里有一个使用
ngMatch directive的例子:
<p>Email:<input type="email" name="email1" ng-model="emailReg"> Repeat Email:<input type="email" name="email2" ng-model="emailReg2" ng-match="emailReg"></p> <span data-ng-show="myForm.emailReg2.$error.match">Emails have to match!</span> 注意:通常不建议使用ng-作为自定义指令的前缀,因为它可能与官方的AngularJS指令冲突。 更新 也可以在不使用自定义指令的情况下获取此功能: HTML <button ng-click="add()></button> <span ng-show="IsMatch">Emails have to match!</span> 控制器 $scope.add = function() { if ($scope.emailReg != $scope.emailReg2) { $scope.IsMatch=true; return false; } $scope.IsMatch=false; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |