user6579134 user6579134 - 2 months ago 11
AngularJS Question

angularjs- disable submit till all fields are filled

Submit button in the form should be disabled till all fields are filled but what i've noticed is when user inputs just the username the button comes alive .

<div class="list">
<form id="create" name="pw" method="post">
<label class="item item-input item-stacked-label">
<span class="input-label">Username</span>
<input type="text" placeholder="kojobaah" ng-model="username" required>
</label>

<label for="password">New Password
<input type="password" name="user_password" ng-model="user_password" ng-required="confirm_password && !user-password" password-verify="confirm_pasword">
<p ng-show="pw.user_password.$error.passwordVerify">Passwords do not match</p>
<p ng-show="pw.user_password.$error.required">This field is required</p>
</label>
</p>
<p>
<label for="password">Confirm Password
<input type="password" name="confirm_password" ng-model="confirm_password" ng-required="user_password && !confirm_password" password-verify="user_password">
<p ng-show="pw.confirm_password.$error.passwordVerify">Passwords do not match</p>
<p ng-show="pw.confirm_password.$error.required">This field is required</p>
</label>
<br />
<p align="center"><button ng-disabled="create.$invalid" class="button button-balanced" ng-click="register()">Create Account</button></p>
</form>
</div>


JS

.directive('passwordVerify', function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elem, attrs, ngModel) {
scope.$watch(attrs.ngModel, function() {
if (scope.confirm_password === scope.user_password) {
scope.pw.confirm_password.$setValidity('passwordVerify', true);
scope.pw.user_password.$setValidity('passwordVerify', true);
} else if (scope.confirm_password !== scope.user_password) {
scope.pw.confirm_password.$setValidity('passwordVerify', false);
scope.pw.user_password.$setValidity('passwordVerify', false);
}
});
}
};
})


any help on how to make the button disabled till username is filled and password matches?

Answer

The name of your form is pw, so that is the form you need to drill into for Angular's validity directive for the form as a whole.

Simply change:

<button ng-disabled="create.$invalid" 
        class="button button-balanced"
        ng-click="register()">
        Create Account
</button>

to:

<button ng-disabled="pw.$invalid" 
        class="button button-balanced"
        ng-click="register()">
        Create Account
</button>

Working Plunker: http://plnkr.co/edit/0zlN2TmEIbGQW5Mq7YJ0?p=preview

Update: Switching ng-required to simply true on the password fields, and moving the comparision logic to the ng-disabled directive on the button achieves the validation check required.

<button ng-disabled="pw.$invalid || (user_password != confirm_password)" 
        class="button button-balanced"
        ng-click="register()">
        Create Account
</button>