Question

I am trying to validate a form using AngularJS. This is my form:

<form ng-controller="LoginCtrl" role="form" class="form-horizontal">
    <div class="form-group">
        <label for="email" class="col-sm-2 control-label">Email</label>
        <div class="col-sm-10">
            <input required type="email" name="email" ng-model="email" class="form-control" ng-class="{ error: email.$invalid }" id="email">
        </div>
    </div>
</form>

The ng-class is never applied. I tried email.$valid, email.$invalid and email.$error. The controller doesn't do anything except for logging to the console, so I know it is called. When I do set $scope.email = 'asd@asd.com' hardcoded it is set correctly though.

Why isn't my ng-class applied when I enter no value or an invalid string?

Was it helpful?

Solution

You must qualify with the form name as well:

<form ng-controller="LoginCtrl" name="emailForm" role="form" class="form-horizontal">
    <div class="form-group">
        <label for="email" class="col-sm-2 control-label">Email</label>
        <div class="col-sm-10">
            <input required type="email" name="email" ng-model="email" class="form-control" ng-class="{ error: emailForm.email.$invalid }" id="email">
        </div>
    </div>
</form>

Angular has its own directive for <form> and therefore understands that if it sees a form, it should add an object to the current scope that is named the same. In this case emailForm. So, in the controller you would address the email field as $scope.emailForm.email.

Since, you are specifically looking for required you could also use this:

ng-class="{ error: emailForm.email.$error.required }"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top