Priyam Mishra
Priyam Mishra

Reputation: 31

AngularJS form with validation

I have created one form with six fields out of which five are mandatory.There is one submit button. If user hasn't entered any input in the textbox and clicks on submit button, all the required textbox should highlight with red border. How to implement it? :-

<div ng-app="myApp" ng-controller="formCtrl">
        <form name="demoForm">
            <label>First Name :</label>
            <input type="text" ng-model="firstName" required/><br><br>
            <label>Last Name :</label>
            <input type="text" ng-model="lastName"/><br><br>
            <label>Email :</label>
            <input type="email" ng-model="emailDet" required/><br><br>
            <label>Contact No :</label>
            <input type="text" ng-model="contactNo" required/><br><br>
            <label>Current Location :</label>
            <input type="text" ng-model="currLoc" required/><br><br>
            <label>Preferred Location :</label>
            <input type="text" ng-model="preLoc" required/><br><br>
            <button type="button" ng-click="onSubmit()">Submit</button>
        </form>
    </div>
    <script>
        var app = angular.module('myApp', []);
        app.controller('formCtrl', function($scope) {
            $scope.onSubmit = function() {

            }
        });
    </script>

Upvotes: 0

Views: 43

Answers (1)

Drag13
Drag13

Reputation: 5978

This is quite easy. Define new css rule like here and all should be fine

.ng-invalid.ng-submitted input {
     border: 1px solid red;
}

Under the hood, angular assign lots of classes to your form and input.

.ng-invalid

signals that something is wrong on the form

.ng-submitted

signals that form was submitted.

And so on. Check documentation and you will find a lot of new findings.

Upvotes: 1

Related Questions