如果在html5表单中需要选择并且未选择任何内容,则所有相应的样式挂钩似乎都有效并且该字段被视为无效,但ng-submit仍然允许表单尝试提交。
为什么会发生这种情况?如果没有选择任何内容(最好没有控制器逻辑),我可以阻止提交吗?
下面是一个最小的示例,其中包含一些样式,以使明显的验证无效:
angular.module('app', []).run(function($rootScope) {
$rootScope.options = ['1', '2', '3'];
$rootScope.attempt = function() {
alert('Attempted with ', $rootScope.selected)
}
});
.form-control.ng-invalid {
color: red;
border: 1px solid red;
}
<!DOCTYPE html>
<html>
<head>
<link data-require="bootstrap-css@*" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
<script data-require="angular.js@1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
</head>
<body ng-app="app">
<p>Selected: {{selected}}</p>
<form ng-submit="attempt()" class="row">
<div class="col-xs-8">
<select class="form-control" ng-model="selected" ng-options="e for e in options" required></select>
</div>
<div class="col-xs-4">
<input class="btn btn-default" type="submit" />
</div>
</form>
</body>
</html>