Reputation: 508
I try to create a form with validation. I am very new at angular.js. I copied some code from samples but I couldn't make it work.
Here is my html and script:
<body ng-app="myApp">
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<h2>Validation Example</h2>
<form name="myForm" novalidate>
<p>Username:<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.required">Username is required.</span>
</span>
</p>
<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>
<label for="password"> Password</label>
<input type="password" name="password" ng-model="password" placeholder="New Password"/>
<label for="confirmPassword">Confirm Password</label>
<input type="password" name="confirmPassword" placeholder="Confirm Password" ng-model="confirmPassword" pw-check="password"/>
<span class="error" ng-show="myForm.password.$error.pwmatch"> Passwords don't match. </span>
<p>
<input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid || myForm.email.$dirty && myForm.email.$invalid">
</p>
</form>
<script>
var app = angular.module('myApp', []);
app.directive('pwCheck', function () {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
scope.$watch(attrs.pwCheck, function (confirmPassword) {
var isValid = ctrl.$viewValue === confirmPassword;
ctrl.$setValidity('pwmatch', isValid);
});
}
}
});
</script>
</body>
Can anyone tell me what is wrong with this ?
Upvotes: 0
Views: 641
Reputation: 419
From what I know about this directive, @dcodesmith's solution is mostly correct. Try this one:
<input type="password" name="confirmPassword" placeholder="Confirm Password" ng-model="confirmPassword" pw-check="password"/>
UPDATE. Sorry for previous snippet. Check this out. This works:
<input type="password" name="password" ng-model="password" placeholder="New Password" pw-check="confirmPassword"/>
<input type="password" name="confirmPassword" placeholder="Confirm Password" ng-model="confirmPassword"/>
JS
link: function (scope, elem, attrs, ctrl) {
scope.$watch(attrs.pwCheck, function (password) {
var isValid = ctrl.$viewValue === password;
ctrl.$setValidity('pwmatch', isValid);
});
}
JSBin: http://jsbin.com/rakivadibi/1/edit?html,js,output
Upvotes: 1