AngularJS Forms & validation
AngularJS form example <input type="text" name="firstName" ng-model="myForm.firstName">First name <input type="text" name="lastName" ng-model="myForm.lastName">Last name {{myForm.firstName}} {{myForm.lastName}} angular.module("myapp", []).controller("MyController", function($scope) { $scope.myForm = {}; $scope.myForm.firstName = "Jakob"; $scope.myForm.lastName = "Jenkov"; } );
Checkboxes and radiobuttons <input type="checkbox" ng-model="myForm.wantNewsletter” ng-true-value="yes" ng-false-value="no" > <input type="radio" ng-model="myForm.whichNewsletter" value="weeklyNews"> <input type="radio" ng-model="myForm.whichNewsletter" value="monthlyNews">
Select <select ng-model="myForm.car" ng-options="obj.id as obj.name for obj in myForm.options“> Please choose a car angular.module("myapp", []).controller("MyController", function($scope) { $scope.myForm = {}; $scope.myForm.car = "nissan"; $scope.myForm.options = [ { id : "nissan", name: "Nissan" }, { id : "toyota", name: "Toyota" }, { id : "fiat", name: "Fiat" }]; } );
Form validation <input type="text" id="name" ng-model="myForm.name" ng-minlength="5" ng-maxlength="12"> Name angular.module("myapp", []).controller("MyController", function($scope) { $scope.myForm = {}; $scope.myForm.name = "Jakob Jenkov"; } ); <input type="text" id="name" ng-model="myForm.name” ng-pattern="/^\d+$/”> ng-required directive checks if the value of the form field is empty or not
Form check results
Using the "name" Attribute <input type="text" ng-model="user.firstLastName" name="firstLastName" placeholder="Enter Name"> Adding the "name" attribute to the form adds the FormController to the scope by that name Adding the "name" attribute to a control with the ngModel directive adds that ngModelController for that control to the FormController This is useful if one wants to check the state of the form or control programmatically
Form and elements validation results
Form check: change css for invalid field <input type="text" ng-class="myFormNg.name.$valid ? ’fieldValid’ : ‘fieldInvalid’ " name="name" ng-model="myForm.name" ng-minlength="2"> Name
Form check: show message <form name="myFormNg" ng-submit="myForm.submitTheForm()" novalidate> <input type="text" ng-class="myForm.getFormFieldCssClass(myFormNg.name2)" id="name1" name="name2" ng-model="myForm.name3" ng-minlength="2"> Name You must enter a valid name. Disable button: Submit
Submitting the form You can submit a form in two ways: Using a button element with an ng-click attribute. Using an ng-submit attribute (directive) on the form element. <input type="text" id="name" ng-model="myForm.name" ng-minlength="5" ng-maxlength="12"> Name Nissan Toyota Fiat
Submitting the form $scope.myForm.submitTheForm = function(item, event) { console.log("--> Submitting form"); var dataObject = { name : $scope.myForm.name, car : $scope.myForm.car }; var p = $http.post(”process.jsp", dataObject, {}); p.success(function(dataFromServer) { console.log(dataFromServer.title); }); p.error(function(data) { alert("Submitting form failed!"); }); }
Custom validation
ngModelController
Parsers and formatters $scope.account.value = ; $ Account value: function format (value) { return "$“+value; } form.acc.$formatters.push(format) function parse(value) { return value.substr(1); } form.acc.$parsers.push(parse); $formatters $parsers
ngModelController
Custom validator ngModel.$validators.onlyNumbers = function(modelValue, viewValue) { var value = modelValue || viewValue; return /[0-9]+/.test(value); }; ngModel.$error.onlyNumbers – results of validation in this method ngModel.$valid – result of validation in all validators
Custom async validator ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) { var value = modelValue || viewValue; return $http.get('/api/users/' + value). // Lookup user then(function resolved() { //username exists, this means validation fails return $q.reject('exists'); }, function rejected() { //username does not exist - this validation passes return true; }); };
Methods to set validity