Thursday, 15 January 2015

javascript - AngularJS 1.3 - why is the form valid on load, for inputs with a minimum length? -



javascript - AngularJS 1.3 - why is the form valid on load, for inputs with a minimum length? -

i getting started angularjs , wish disable submit button of form, if form has any fields invalid.

i have field called title. has requirement minlength 5. on load of form, form object provided angularjs reports $invalid: false

<div ng-controller="newpinctrl newpin"> <form role="form" name="formnewpin"> <div> <label>title</label> <input ng-model="newpin.pin.title" ng-minlength="5" ng-maxlength="140" type="text" name="title" value="" placeholder="title" /> <ul ng-messages="formnewpin.title.$error" ng-if="formnewpin.title.$dirty"> <li ng-message="required">this required</li> <li ng-message="minlength">should longer 5 characters</li> <li ng-message="maxlength">should shorter 140 characters</li> </ul> </div> </form> </div>

and here button:

<button ng-click="newpin.savepin()" ng-disabled="formnewpin.$pristine || formnewpin.$invalid" type="button">submit</button>

fine thought, i'll disable button if form $pristine: true. solved 'on load' issue...but when user clears field , goes blank, $invalid reports false.

why this, when field has minlength requirement? and, how can around without checking each form field error individually?

thanks!

edit: might add, i'm using new ngmessages 1.3

you have provided message required error, haven't marked input required. that's why evaluated valid on first load.

after adding required attribute, won't need using ng-if ng-messages. final solution should this:

<form name="formnewpin"> <label>title</label> <input ng-model="newpin.pin.title" required ng-minlength="5" ng-maxlength="140" type="text" name="title" value="" placeholder="title"> <ul ng-messages="formnewpin.title.$error"> <li ng-message="required">this required</li> <li ng-message="minlength">should longer 5 characters</li> <li ng-message="maxlength">should shorter 140 characters</li> </ul> <button ng-click="newpin.savepin()" ng-disabled="formnewpin.$invalid" type="button">submit</button> </form>

plunker this.

javascript angularjs

No comments:

Post a Comment