Step 1.2. Form Validation

With Login form, we have some requirements:

  • ❏ Username and password are required

  • ❏ Username have to be a valid email

  • ❏ Login button is diabled util the form isn’t valid

  • ❏ Show required or invalid errors.

  • ❏ Show success message if submitted ok.

Upgrade login.html

<ion-view title="Please sign in">
    <ion-content class="padding">
        <form name="loginForm" ng-submit="vm.login(loginForm.$valid)" novalidate>
            <div class="list">
                <label class="item item-input">
                    <input type="email" placeholder="Enter Email" name="username"
                        ng-model="vm.user.username" required>
                </label>
                <p ng-show="loginForm.username.$invalid && !loginForm.username.$pristine"
                    class="help-block">Email is required and must be valid.</p>
                <label class="item item-input">
                    <input type="password" placeholder="Enter Password" name="password"
                        ng-model="vm.user.password" required>
                </label>
                <p ng-show="loginForm.password.$invalid && !loginForm.password.$pristine"
                    class="help-block">Password is required.</p>
            </div>
            <button class="button button-full button-balanced" type="submit" ng-disabled="loginForm.$invalid">
                Login
            </button>
            <button class="button button-positive button-clear button-full" ui-sref="public.register">Register now!</button>
        </form>
    </ion-content>
</ion-view>
First change: We add form tag to wrap all input fields.

ng-submit bind submit event of form to login method of controller. And loginForm.$valid will represent the valid state of form. A form is valid when all its input fields are valid.

novalidate is an attribute to turn off default HTML5 validations.

Second change: Add required validation to username field.

Because we use email as username, so we change type of input field from text to email. required is an attribute to mark this field is required.

The p tag with ng-show will displayed when the condition is true. Here we show error message if the username field is invalid and not pristine means it’s dirty, inputted something.

Third change: we do the same with Password field.
Fourth change: We disable Login button when the form isn’t valid.

ng-disabled will disable the element when the condition is true.

The last thing, we need modify login method a bit:

function login(isValid) {
    if(!isValid){
      return;
    }
    AuthService.auth(vm.user).then(function(response){
      // on success
      console.log(response);
    }).catch(function(error){
      // on error
      console.log(error);
    });
  }

Here we will not call service if the form isn’t valid.