In previous posts, we learnt how to work with different html form elements. In this post, we shall learn how to bind the custom error message to the form and based on the control state.
Important: It's important go through previous posts before going through this post to understand it completely.
The form and its control state can be validated based on following properties of the form and its control
$touched
- This property is used with HTML element to know whether user has interacted with this element$submitted
- This property is used with HTML form to know whether user has submitted the formIn the <script> block, under FormController
we have declared a Main property that is an empty object. Apart from this we have two function declared
$scope.Submit
- method is used to simply set the Main property to the form elements property$scope.Reset
- method is used to reset the form state to Pristine (not interacted) mode and untouched (element has not lost its focus ie user is still in the control) mode by calling $setPristine()
and $setUntouced()
method.<script>
var app = angular.module("app", []);
app.controller("FormController", ['$scope', function ($scope) {
$scope.Main = {};
$scope.Submit = function (PD) {
$scope.Main = angular.copy(PD);
};
$scope.Reset = function (myForm) {
if (myForm) {
myForm.$setPristine();
myForm.$setUntouched();
}
$scope.PD = angular.copy($scope.Main);
};
}]);
</script>
<form ng-app="app" ng-controller="FormController" name="myForm" novalidate>
<p>
First name: <input type="text" name="FirstName" ng-model="PD.firstName" required />
<span ng-show="myForm.$submitted">
<label ng-show="myForm.FirstName.$error.required">First name is required !</label>
</span>
</p>
<p>
Last name: <input type="text" name="LastName" ng-model="PD.lastName" required />
<span ng-show="myForm.LastName.$touched">
<label ng-show="myForm.LastName.$error.required">Last name is required !</label>
</span>
</p>
<p>
Active: <input type="checkbox" name="Active" ng-model="PD.active" required />
<label ng-show="PD.active">
<input type="text" name="ActiveConfirm" ng-model="PD.activeConfirm" required />
</label>
<span ng-show="myForm.$submitted">
<label ng-show="myForm.ActiveConfirm.$error.required">Active is required !</label>
</span>
</p>
<input type="button" ng-click="Reset(myForm)" value="Reset" />
<input type="submit" ng-click="Submit(PD)" value="Submit" />
</form>
In the HTML block, we have following (To know more about different form property, read this posts)
ng-show
by checking whether form is submitted (myForm.$submitted
where myForm is the name of the form).