how to validate form in ionic using angular js

17,482

I might be late but here's what you can do.

First of all you need to define a form (as you did) using the ng-submit directive so that your form can be POST to the controller.

<body ng-app="myApp">
   <ion-view title="Page">
    <ion-content padding="true" class="has-header has-footer">
        <form name="loginForm" ng-submit="$scope.login($scope.user);" novalidate>
            <label class="item item-input">
                <span class="input-label">name</span>
                <input type="text" placeholder="name" ng-model="$scope.user.username" form-validate-after>
            </label>
            <label class="item item-input">
                <span class="input-label">email</span>
                <input type="email" placeholder="email" ng-model="$scope.user.email" form-validate-after>
            </label>
            <label class="item item-input">
                <span class="input-label">password</span>
                <input type="password" placeholder="password" ng-model="$scope.user.password" form-validate-after>
            </label>
        </form>
        <button class="button button-balanced button-block">check validation</button>
    </ion-content>
</ion-view>
</body>

I am passing a model to my input field so I can read them later. I've marked each input with a custom directive form-validate-after.

This is the directive I've created:

(function () {

    'use strict';

    angular
        .module('myApp', ['ionic'])
        .directive('formValidateAfter', formValidateAfter);

    function formValidateAfter() {
        var directive = {
            restrict: 'A',
            require: 'ngModel',
            link: link
        };

        return directive;

        function link(scope, element, attrs, ctrl) {
            var validateClass = 'form-validate';
            ctrl.validate = false;
            element.bind('focus', function (evt) {
                if (ctrl.validate && ctrl.$invalid) // if we focus and the field was invalid, keep the validation
                {
                    element.addClass(validateClass);
                    scope.$apply(function () { ctrl.validate = true; });
                }
                else {
                    element.removeClass(validateClass);
                    scope.$apply(function () { ctrl.validate = false; });
                }

            }).bind('blur', function (evt) {
                element.addClass(validateClass);
                scope.$apply(function () { ctrl.validate = true; });
            });
        }
    }

}());

this code will loop through all your input fields adding a class if it is marked as non-valid.

You need to define a css:

.form-validate.ng-invalid {
    border: 3px solid #cc2511;
}
.form-validate.ng-valid {
    border: none;
}

don't forget to add novalidate to your form.

novalidate is used to disable browser's native form validation.

If you want to set a field as mandatory and define max and min lenght:

<input name="password" type="password" placeholder="password" ng-model="$scope.user.password" required ng-minlength='5' ng-maxlength='10'>

If you want to see this sample in action you can check it here.

UPDATE

Another approach is to set everything in-line changing class on each label:

<label class="item item-input" ng-class="{ 'has-errors' : loginForm.username.$invalid && !loginForm.username.$pristine, 'no-errors' : loginForm.username.$valid}">
   ...
</label>

Here you have to give each field a name and use ng-class directive.

The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.

You can see it in action here.

Share:
17,482
Shruti
Author by

Shruti

Updated on June 16, 2022

Comments

  • Shruti
    Shruti almost 2 years

    I am trying to use the ionic framework with angular.I want to do validation of my form on button click.Mean I need to validate all field on button click.All field are required ..I need to show an error message if a field does not fulfil the requirement. Like password minimum character 5 and maximum 10. And email validation.

    could you please tell m how I will do validation.Here is my code

    <html ng-app="">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    
        <title>Sign-in, Then Tabs Example</title>
    
        <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
        <script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
    
      </head>
    
      <body>
    
        <ion-view title="Page">
        <ion-content padding="true" class="has-header has-footer">
            <form>
                <label class="item item-input">
                    <span class="input-label">name</span>
                    <input type="text" placeholder="name">
                </label>
                <label class="item item-input">
                    <span class="input-label">email</span>
                    <input type="email" placeholder="email">
                </label>
                <label class="item item-input">
                    <span class="input-label">password</span>
                    <input type="password" placeholder="password">
                </label>
            </form>
            <button class="button button-balanced button-block">check validation</button>
        </ion-content>
    </ion-view>
    
      </body>
    </html>