AngularJS validation ng-invalid class only after s

2019-08-10 12:37发布

问题:

In my from I have several inputs with validation, I need for the ng-invalid class to only be applied once the user has submitted the form.

On submit I can set a value on the scope as such...

$scope.submitForm = function () {
    $scope.submited = true;
    // other bits
}

... but I cant figure out how to conditionally display ng-invalid without changing the validation itself.

I am running angular 1.1.5

回答1:

Demo

 <input type="email" name="email" ng-model="formData.email" required />
<span ng-show="(myForm.email.$dirty || submitted) && myForm.email.$error.required">
  Email is required
</span>

Use $dirty flag to show the error only after user interacted with the input:



回答2:

<div ng-app>
<div ng-controller="testController">
    <form name="formValidate">
    <input type="text" name="testing" required ng-model="testField" ng-class="{ invalid: submitted && formValidate.testing.$invalid }"/>
        <button ng-click="test()">Test</button>
        </form>
</div>
</div>
<script>
    var app = angular.module('', []);
function testController($scope)
{
    $scope.submitted = false;
    $scope.test= function()
    {
        $scope.submitted = true;    
        console.log($scope.formValidate.$invalid);
    }
}
</script>
<style>
    .invalid
{
    border:1px solid red;   
}
</style>


回答3:

For custom errors I suggest to use the $setValidity method within each field.

$scope.formName.fieldName.$setValidity('custom_error_name', true);

so you will have more control over the css part too, because this kind of workflow will create also a custom class inside your field like "ng-custom_error_name" so you can deal with that.