AngularJS - Form Validation
FormController, ng-show, ng-if, ng-model, ng-messages
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
<body translate="no">
<button ng-click="checkall()">check all</button>
<body ng-app="app" ng-controller="myCtrl">
<div ng-repeat="user in users">
<script type="text/ng-template" id="generic-messages">
<p ng-message="required">This field is required.</p>
<p ng-message="minlength">This field is too short.</p>
<p ng-message="maxlength">This field is too long.</p>
</script>
<form name="forms[{{$index}}]">
<button ng-click="myFunc($index)">check {{$index}}</button>
<label>Username (Using Dirty)</label>
<input type="text" name="username" ng-model="user.inputName" ng-minlength="6" ng-maxlength="12" ng-pattern="/^\w+$/" required>
<div ng-messages="forms[$index].username.$error" ng-show="forms[$index].$submitted">
<p ng-message="pattern">Username can only be alphanumeric with an optional underscore.</p>
<p ng-message="maxlength">Username cannot be longer than 12 characters.</p>
<p ng-message="minlength">Username must be longer than 2 characters.</p>
<div ng-messages-include="generic-messages"></div>
</div>
<label>Password (Using Touched)</label>
<input type="text" name="userPassword" ng-model="user.inputPassword" ng-minlength="6" ng-maxlength="12" required>
<div ng-messages="forms[$index].userPassword.$error" ng-show="forms[$index].$submitted">
<div ng-messages-include="generic-messages"></div>
</div>
<label>Email (Using Dirty)</label>
<input type="email" name="userEmail" ng-model="user.inputEmail" required>
<div ng-messages="forms[$index].userEmail.$error" ng-show="forms[$index].$submitted">
<p ng-message="required">This field is required.</p>
<p ng-message="email">Please...
CSS
body {
font-family: 'Lato';
margin: 20px;
font-weight: 400;
}
label {
color: #555;
font-weight: bold;
margin-right: 10px;
display: block;
}
input {
border: 2px solid #2196F3;
width: 300px;
outline: none;
padding: 4px;
border-radius: 5px;
margin: 5px 0 10px 0;
}
p {
color: red;
font-weight: bold;
padding: 0;
margin: 5px 0 40px 0;
}
JavaScript
var app = angular.module("app", ['ngMessages']);
app.controller("myCtrl", function($scope) {
$scope.forms = [];
$scope.users = [{
"inputName": "aj",
"inputPassword": "1234",
"inputEmail": "aj@g.in",
}, {
"inputName": "gj",
"inputPassword": "1234",
"inputEmail": "gj@g.in",
}];
$scope.myFunc = function(formIndex) {
console.log(formIndex);
//console.log($scope.forms[formIndex]);
};
$scope.checkall = function(form) {
$scope.forms[0].$setSubmitted();
$scope.forms[1].$setSubmitted();
console.log('form 1 is valid: ', $scope.forms[0].$valid);
console.log('form 1 username field', $scope.forms[1].username);
console.log('form 2 is valid: ', $scope.forms[1].$valid);
};
});