ng-required not working when submitting a form

混江龙づ霸主 提交于 2020-01-03 16:56:32

问题


I have the following code in an input text box with the required attribute, but when I tab off of the field or submit the form, it doesn't stop the form from submitting and informing the user the field is required.

<div class="col-sm-8">
   <input type="text" ng-required="true" class="form-control" 
    placeholder="Enter Total Amount" id="txtTotalAmount" 
    ng-model="formCtrl.AddCheckDeposit.TotalAmount" />
</div>

What do I need to do to make the required directive to work?


回答1:


For that you should fire ng-submit event when form is valid

ng-submit="myForm.$valid && submit()"

Seems like you have also missed the name attribute on your input field, also for showing an error you could use ng-show/ng-messages directive

<form name="myForm" ng-submit="myForm.$valid && submit()">
   <div class="col-sm-8">
      <input type="text" ng-required="true" class="form-control" placeholder="Enter Total Amount" name="txtTotalAmount"
       id="txtTotalAmount" ng-model="formCtrl.AddCheckDeposit.TotalAmount" />
      <span ng-show="myForm.txtTotalAmount.$error.required">Required</span>
   </div>  
</form>


来源:https://stackoverflow.com/questions/33001589/ng-required-not-working-when-submitting-a-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!