0

I have a similar code like the one below for a registration form. In this example the email value is preload therefor the error is not shown. But how can I avoid the error when there is no preload value, in other words when the value is empty like:

$scope.Email = {valor:""};

Here is the example:

<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Example - example-example59-production</title>


  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.1/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.1/angular-animate.js"></script>

</head>

<body ng-app="formExample">
  <script>
    angular.module('formExample', [])
      .controller('FormController', ['$scope',
        function($scope) {
          $scope.Email = {
            valor: "a@a.com"
          };
        }
      ]);
  </script>
  <style>
    .my-form {
      transition: all linear 0.5s;
      background: transparent;
    }
    .my-form.ng-invalid {
      background: red;
    }
  </style>
  <form name="myForm" ng-controller="FormController">
    Email:
    <input name="input" ng-model="Email.valor" required class="my-form">
    <span class="error" ng-show="myForm.input.$error.required">Required!</span>
    <br>
    <code>userType = {{Email.valor}}</code>
    <br>
    <code>myForm.input.$valid = {{myForm.input.$valid}}</code>
    <br>
    <code>myForm.input.$error = {{myForm.input.$error}}</code>
    <br>
    <code>myForm.$valid = {{myForm.$valid}}</code>
    <br>
    <code>myForm.$error.required = {{!!myForm.$error.required}}</code>
    <br>
  </form>
</body>

</html>
ElektroStudios
  • 19,105
  • 33
  • 200
  • 417
lito
  • 3,105
  • 11
  • 43
  • 71
  • Are you intentionally validating the email on page load for any reason? Or is that a side-affect of the way you designed your code? – Mark C. Nov 03 '15 at 02:28
  • Oh, I just realized you copied the exact example from the [documentation](https://docs.angularjs.org/api/ng/directive/form) ... What have you tried and what didn't work? – Mark C. Nov 03 '15 at 02:33

2 Answers2

1

You can just hide the error if the form is pristine (ie, the input hasn't been altered yet). Something like:

<code ng-if='myForm.myControl.$dirty'>myForm.$error.required = {{!!myForm.$error.required}}</code><br>

If that's what you're looking for, there's a thread with more detail over here: How to make ngMessage for required fields only show when dirty or submitting a form?

Community
  • 1
  • 1
Andrew Cavanagh
  • 277
  • 2
  • 14
1

Change your css Replace by this

input.ng-invalid.ng-dirty {
      background-color: #FA787E;
    }

    input.ng-valid.ng-dirty {
      background-color: #78FA89;
    }

Instead of

.my-form {
      transition: all linear 0.5s;
      background: transparent;
    }
    .my-form.ng-invalid {
      background: red;
    }
Shohel
  • 3,886
  • 4
  • 38
  • 75