问题
I've gotten an example of form validation working correctly in my app for the login page, looking something like this:
<div class="form-group" >
<label for="password">Password</label>
<input type="password"
id="password"
name="password"
class="form-control"
placeholder="Create password"
ng-model="password"
required
minlength="{{passwordLength}}"
>
<div class="help-block text-danger"
ng-messages="form.password.$error"
ng-if="form.password.$touched || form.$submitted"
>
<div class="text-danger">
<div ng-message="required">A password is required</div>
<div ng-message="minlength" >Password must be at least {{passwordLength}} characters</div>
</div>
</div>
</div>
This works great for "required" and "minlength" checks, which can be done before submission. However after submission, we can get back a 401 for an invalid username/password. Angular 1.3 has an async validaiton concept, but it seems to run before submission, and it seems unreasonable to try to login twice (once just to see if they could and prompt an error)
Is there a reasonable way to use the ng-messages concept to display this post-submission error?
回答1:
I figured it out. You can just manually validate/invalidate the form:
<div class="help-block text-danger">
<div class="text-danger"
ng-messages="form.password.$error"
ng-if="form.password.$touched || form.$submitted">
<div ng-message="required">Password is required</div>
<div ng-message="minlength">*Password must be at least {{passwordLength}} characters</div>
<div ng-message="correctPassword">Username/Password combination is incorrect</div>
</div>
</div>
and in your controller, on submit:
$scope.login = function(){
$scope.form.password.$setValidity("correctPassword", true);
// ...do some stuff...
$http.post('/someUrl', {msg:'hello word!'})
.success(function(){})
.error(function() {
$scope.form.password.$setValidity("correctPassword", false);
});
}
来源:https://stackoverflow.com/questions/26789299/using-angular-1-3-ngmessage-for-form-submission-errors