Abdul Rehman Sayed Abdul Rehman Sayed - 5 months ago 10
AngularJS Question

why are validation directives/properties not set on field?

See this plunkr :

https://plnkr.co/edit/vQvgVSAfMLh3kPRKDFP2?p=preview

I have written minlength, maxlength & validation attributes on the mname field but their $valid,$dirty & $pristine properties are somehow not being set. & thus I am unable to show error messages.

I can verify that form is invalid by passing the form to the controller & adding an alert there.

HTML Code

<!doctype html>
<html ng-app="emi" >
<head>
<meta charset="utf-8">
<title>Empty AngularJS</title>
<link rel="stylesheet" href="style.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.18/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.18/angular-messages.js"></script>
<script src="script.js"></script>
</head>
<body>

<section data-ng-controller="emiController">
<h1>{{title}}</h1>

<form name="MyEmiForm" novalidate data-ng-submit="create(MyEmiForm)" >

<div>
<label for="name">Name</label>
<div>
<input type="text" data-ng-model="name" id="mname"
placeholder="Name" required ng-minlength="3" ng-maxlength="8"/>


<br>
Form Valid : {{MyEmiForm.$valid }} <br>
{{MyEmiForm.mname.$error }}<br>
mname Valid : {{MyEmiForm.mname.$valid }}<br>
mname Dirty : {{MyEmiForm.mname.$dirty }}<br>
mname Pristine : {{MyEmiForm.mname.$pristine}}<br>
mname Touched : {{MyEmiForm.mname.$touched }}<br>
DOB Valid : {{MyEmiForm.dob.$valid }}<br>

<span class="help-block"
ng-show="MyEmiForm.mname.$invalid && !MyEmiForm.mname.$pristine">
You name is required.
</span>


<div ng-messages="MyEmiForm.mname.$error" >
<div ng-message="required">This field is required</div>
</div>
</div>
</div>

<div>
<label for="dob">DOB</label>
<div>
<input type="text" data-ng-model="dob" id="dob" placeholder="DOB" required/>
</div>
</div>

<div>
<input type="submit" >
</div>
<div data-ng-show="error">
<strong data-ng-bind="error"></strong>
</div>
</form>
</section>
</body>
</html>


Script File

angular.module('emi', ['ngMessages']) //[] re-initialize, w/o []. use exiting
.controller('emiController',
['$scope' ,
function($scope)
{

$scope.title = "New Emi Calculation";

$scope.create = function(form) {
if(!form.$valid)
{
alert("Not ok");
return;
}
alert("All ok");
}


}
]);

Answer

add name attribute to input

<input type="text"  name='mname' data-ng-model="name" id="mname"  
            placeholder="Name" required ng-minlength="3" ng-maxlength="8"/>