Form Handling and Validation in AngularJS

Updated on     Kisan Patel

AngularJS provide a nice form API that, not only lets you bind form controls to scope models, but also allows you to validate each control easily. Now, we will focus on form handling and validation in AngularJS.

In this example, we will create a form to enter student details and capture entered student information in a scope.

Here, we can use the standard HTML form tag and the ng-model directive to implement a basic form:

<div ng-app="app" ng-controller="studentController">
   <form ng-submit="submit()" novalidate>
      <p>
         <label>Name</label>
         <input type="text" ng-model="student.Name" />
      </p>
      <p>
         <label>Roll No.</label>
         <input type="text" ng-model="student.RollNo" />
      </p>
      <input type="submit" value="Submit">
   </form>
</div>

Here, the novalidate attribute disables the HTML5 validations, which are client-side validations supports by modern browsers.

The controller studentController binds the form data to your student model and implements the submit() function as shown below:

<script type="text/javascript">
var myModule = angular.module("app", []);

myModule.controller('studentController', function ($scope) {

     $scope.student = {};

     $scope.submit = function() {
         console.log("Student created successfully: " + $scope.student);
         //Use $http service to save student data
     };
});
</script>

AngularJS

Leave a Reply