stalwalk
stalwalk

Reputation: 113

Why is the angular form validation applying incorrect CSS styles?

I need help understanding form validation with angularjs 1.5.

I have a form with a First Name field which is required. The Last Name is NOT required. When I click in Last Name and then don't type anything and click out, I see that it shows a Red Border. I would expect a green border.

I have css styles for ng-valid and ng-touched to show a green border and ng-invalid and ng-touched to show a red border. If I just click inside Last Name and then click out, then i see that the css style for ng-invalid ng-touched is shown and I see that a red border is shown. Why do I see a red border when the field is NOT required and the error object is blank.

(function(){
  'use strict';
  var app = angular.module('demoApp', ['ui.router']);
  app.controller('SignupController', SignupController);
  SignupController.$inject=['$rootScope'];
  function SignupController(){
    var ctrl = this;
    ctrl.userName = "";
    ctrl.lastName = "";
  }
})();
.ng-invalid .ng-touched  {
  border: 2px solid red;
}
.ng-valid .ng-touched  {
  border:2px solid green;
}
<!DOCTYPE html>
<html ng-app='demoApp'>
<head>
  <title>Forms {{10+20}}</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.0-beta.2/angular-ui-router.js"></script>

  <script src="script.js"></script>
  <link rel="stylesheet"  href="style.css">
</head>
<body ng-controller="SignupController as ctrl">
  <h1>World of Forms{{10+20}}</h1>

  <fieldset>
    <legend>Signup</legend>
    <form name="signupForm" novalidate>
    <br/>First Name*: <input type="text" required id="userName" name="userName" ng-model='userName'>
    <span ng-if='signupForm.userName.$error.required && signupForm.userName.$touched'>Name is Required</span>
   
    <br/>
    <br/>Last Name: <input type="text" id="lastName" name="lastName" ng-model='lastName'>
    <span>Error:{{signupForm.lastName.$error | json}}</span>
    </form>
  </fieldset>
</body>
</html>

Upvotes: 1

Views: 1880

Answers (1)

AHAY
AHAY

Reputation: 191

I think your problem lies within your css:

.ng-invalid .ng-touched  {
  border: 2px solid red;
}

If you touch the field, no matter what, your field will get the ng-touched class applied to it, which makes it have the red border.

Perhaps try this instead:

.ng-invalid.ng-touched  {
  border: 2px solid red;
}

.ng-valid.ng-touched  {
  border:2px solid green;
}

Upvotes: 2

Related Questions