使用 AngularJS 比较表单验证中的两个输入值 [英] Comparing two input values in a form validation with AngularJS
问题描述
我正在尝试使用 AngularJS 进行表单验证.我对比较两个值特别感兴趣.我希望用户在继续之前确认他输入的一些数据.假设我有以下代码:
I am trying to do a form validation using AngularJS. I am especially interested in comparing two values. I want the user to confirm some data he entered before he continues. Lets say I have the code below:
<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 将对输入中的文本做出正确反应,除非我不知道如何在此验证中使用比较来强制电子邮件在允许用户提交表单之前相同.
registerForm.$valid will react correctly as to the text in inputs except I do not know how to use comparison within this validation to force the emails to be the same before allowing the user to submit the form.
我希望有一个没有自定义指令的解决方案,但如果没有它就无法实现,我会处理它.这里是解决类似问题的答案使用自定义指令.
I would love to have a solution without custom directives, but if this can't be achieved without it I will deal with it. Here is an answer that addresses similar issue with a custom directive.
感谢任何帮助,谢谢
推荐答案
实现此目的的一种方法是使用自定义指令.下面是一个使用自定义指令的示例(在本例中为 ng-match
):
One way to achieve this is with a custom directive. Here's an example using a custom directive (ng-match
in this case):
<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 指令冲突.
NOTE: It's not generally recommended to use ng-
as a prefix for a custom directive because it may conflict with an official AngularJS directive.
也可以在不使用自定义指令的情况下获得此功能:
It's also possible to get this functionality without using a custom directive:
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;
}
这篇关于使用 AngularJS 比较表单验证中的两个输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!