我有一个棱角分明的形状。我正在尝试在必需的字段上实现一些验证,例如this很好的教程,其中说angular具有“内置”功能。但是 - 它不适合我。当我在没有填写字段的情况下提交表单时,没有任何反应。谁能明白为什么?
<form id = "myForm" name="myForm" novalidate>
<div class="form-group" ng-class="{ 'has-error' : myForm.name.$invalid && !myForm.name.$pristine && submitted }">
<input type="text" name="name" class="form-control" ng-model="company.name" required>
<p ng-show="myForm.name.$invalid && !myForm.name.$pristine" >Your firm's name is required.</p>
</div>
<br />
<br />
<div class="form-group" ng-class="{ 'has-error' : myForm.address.$invalid && !myForm.address.$pristine && submitted }">
<input type="text" class="form-control" id = "address" name="address" ng-model="company.address" required>
<p ng-show="myForm.address.$invalid && !myForm.address.$pristine" class="help-block">Your address is required.</p>
</div>
<button type="submit" ng-click= "createAccount()" class="btn btn-small btn-primary">GO
</button>
</form>
我还在我的createAccount()函数中包含了$scope.submitted = true;
。
答案 0 :(得分:2)
请记住,AngularJS是一个客户端框架。您必须在提交内容之前执行验证。
将ng-disabled
添加到您的提交按钮:
<button type="submit" ng-disabled="myForm.$invalid" ng-click= "createAccount()" class="btn btn-small btn-primary">GO</button>
或者检查createAccount()
函数中的验证状态,如您所指的教程示例中所示:
if (!$scope.myForm.$valid) {
alert('Something is wrong');
}