Currently, my form consists of just one field with a few validation rules:
<form name="my_form" novalidate ng-controller="FormController">
<label>Your Name:</label>
<input type="text"
name="name"
placeholder="Your Name"
ng-model="form.name"
ng-minlength="3"
ng-maxlength="20"
unique
required />
<button ng-click="submitForm()">Submit</button>
<div class="error"
ng-show="my_form.isSubmitted"
ng-messages="my_form.name.$error">
<div ng-messages-include="errors.html"></div>
</div>
</form>
The field undergoes validation for:
- Minimum length
- Maximum length
- Required input
- Uniqueness (custom validation rule)
I utilize ng-messages to exhibit error messages close to the input field. Here's my errors.html template:
<div ng-message="required">This field is required.</div>
<div ng-message="minlength">This field is too short.</div>
<div ng-message="maxlength">This field is too long.</div>
<div ng-message="unique">The value of this field must be unique.</div>
Validation only commences post the 'Submit' button click (submitForm() function triggers my_form.isSubmitted flag and releases my error div).
Below is my JavaScript code:
var app = angular.module('formValidation', ['ngMessages']);
app.controller('FormController', function($scope) {
$scope.submitForm = function() {
$scope.my_form.isSubmitted = true;
};
});
app.directive('unique', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, ele, attrs, ctrl) {
var names = ['Dmitry', 'Alexander', 'Elizabeth'];
ctrl.$parsers.push(function(value) {
if (names.indexOf(value) > -1) {
ctrl.$setValidity('unique', false);
return false;
}
ctrl.$setValidity('unique', true);
return true;
});
}
};
);
While everything functions smoothly, I now aim to hide errors upon field modification after they've been displayed (until the submit button is pressed again).
One approach could be adding another condition to the ng-show directive of the error div to verify if the corresponding field is updated. If so, errors should stay hidden. For instance:
<div class="error"
ng-show="!my_form.name.isUpdated && my_form.isSubmitted"
ng-messages="my_form.name.$error">
<div ng-messages-include="errors.html"></div>
</div>
Thus, on button press, I can set the isUpdated flag of all form fields to false and update it to true on any input changes. However, this solution feels somewhat inelegant. I'm certain there exists a better method to achieve this behavior. Any suggestions?