Trigger validation of all fields in Angular Form submit

后端 未结 13 1339
悲哀的现实
悲哀的现实 2020-12-08 01:45

I\'m using this method: http://plnkr.co/edit/A6gvyoXbBd2kfToPmiiA?p=preview to only validate fields on blur. This works fine, but I would also like to validate them (and thu

相关标签:
13条回答
  • 2020-12-08 02:25

    You can try this:

    // The controller
    
    $scope.submitForm = function(form){
       		//Force the field validation
       		angular.forEach(form, function(obj){
       			if(angular.isObject(obj) && angular.isDefined(obj.$setDirty))
       			{ 
       				obj.$setDirty();
       			}
       		})
            
            if (form.$valid){
    		
    			$scope.myResource.$save(function(data){
    		     	//....
    			});
    		}
    }
    <!-- FORM -->
    
      <form name="myForm"  role="form" novalidate="novalidate">
    <!-- FORM GROUP to field 1 -->
      <div class="form-group" ng-class="{ 'has-error' : myForm.field1.$invalid && myForm.field1.$dirty }">
          <label for="field1">My field 1</label>
            <span class="nullable"> 
            <select name="field1" ng-model="myresource.field1" ng-options="list.id as list.name for list in listofall"
              class="form-control input-sm" required>
                <option value="">Select One</option>
            </select>
            </span>
            <div ng-if="myForm.field1.$dirty" ng-messages="myForm.field1.$error" ng-messages-include="mymessages"></div>
      </div>
        
    <!-- FORM GROUP to field 2 -->
      <div class="form-group" ng-class="{ 'has-error' : myForm.field2.$invalid && myForm.field2.$dirty }">
        <label class="control-label labelsmall" for="field2">field2</label> 
          <input name="field2" min="1" placeholder="" ng-model="myresource.field2" type="number" 
          class="form-control input-sm" required>
        <div ng-if="myForm.field2.$dirty" ng-messages="myForm.field2.$error" ng-messages-include="mymessages"></div>
      </div>
    
      </form>
    
    <!-- ... -->
    <button type="submit" ng-click="submitForm(myForm)">Send</button>

    0 讨论(0)
提交回复
热议问题