Javascript AngularJS表单验证未按预期工作
当我为submit按钮添加ng disabled指令的附加检查时,以下代码(取自W3Schools)不起作用。我想使用“myForm.email.$untouched”,这样当有人立即进入页面且字段为空时,提交按钮将被禁用。但是当我添加它时,我必须单击某个地方,然后按钮才被启用Javascript AngularJS表单验证未按预期工作,javascript,jquery,html,angularjs,Javascript,Jquery,Html,Angularjs,当我为submit按钮添加ng disabled指令的附加检查时,以下代码(取自W3Schools)不起作用。我想使用“myForm.email.$untouched”,这样当有人立即进入页面且字段为空时,提交按钮将被禁用。但是当我添加它时,我必须单击某个地方,然后按钮才被启用 <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angul
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<h2>Validation Example</h2>
<form ng-app="myApp" ng-controller="validateCtrl" name="myForm" novalidate>
<p>Email:
<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>
<p>
<button ng-disabled="myForm.email.$dirty && myForm.email.$invalid">Absenden</button>
</p>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
$scope.user = 'John Doe';
$scope.email = '';
});
</script>
</body>
</html>
验证示例
电邮:
电子邮件是必需的。
无效的电子邮件地址。
阿本登
var-app=angular.module('myApp',[]);
app.controller('validateCtrl',函数($scope){
$scope.user='John Doe';
$scope.email='';
});
要将代码更改为此,但它不起作用(必须单击某个位置):
阿本登
试试这个条件
<p>
<button ng-disabled="myForm.email.$touched && myForm.email.$dirty && myForm.email.$invalid">Absenden</button>
</p>
阿本登
您必须更改
<p>
<button
ng-disabled="myForm.email.$untouched || myForm.email.$dirty && myForm.email.$invalid">Absenden</button>
</p>
阿本登
到
阿本登
使用$pristine`as而不是$untouched
<p>
<button
ng-disabled="myForm.email.$untouched || myForm.email.$dirty && myForm.email.$invalid">Absenden</button>
</p>
<p>
<button
ng-disabled="myForm.email.$dirty && myForm.email.$invalid || myForm.email.$pristine">Absenden</button>
</p>