Angular is automatically adding 'ng-invalid' class on 'required' fields

后端 未结 5 1160
暖寄归人
暖寄归人 2020-12-24 05:41

I am building an angular app for which I have some forms set up. I have some fields that are required to be filled before submission. Therefore I have added \'required\' on

5条回答
  •  一整个雨季
    2020-12-24 06:29

    Try to add the class for validation dynamically, when the form has been submitted or the field is invalid. Use the form name and add the 'name' attribute to the input. Example with Bootstrap:

    It is also important, that your form has the ng-submit="" attribute:

    ....

    You can also add an optional function for validation to the form:

    //within your controller (some extras...)
    
    $scope.checkSubmit = function () {
    
       if ($scope.myForm.$valid) {
            alert('All good...'); //next step!
    
       }
       else {
            alert('Not all fields valid! Do something...');
        }
    
     }
    

    Now, when you load your app the class 'has-error' will only be added when the form is submitted or the field has been touched. Instead of:
    !myForm.username.$pristine

    You could also use:
    myForm.username.$dirty

提交回复
热议问题