I have a validation.js file that checks if a field is valid
exports.user = {
username: function(input) {
if (!input)
return 'username is required'
var min = 3
var max = 10
if (input.length < min)
return 'username min of length is ' + min
if (input.length > max)
return 'username max of length is ' + max
return null
},
password: function(input) {
if (!input)
return 'password is required'
var min = 3
var max = 10
if (input.length < min)
return 'password min of length is ' + min
if (input.length > max)
return 'password max of length is ' + max
return null
}
}
This is my sign in form (i just show the username field)
<div ng-if="showSignin" class="my-tab-pane">
<form name="signin_form" action="{{signinServerUrl}}" method="POST">
<div class="my-form-group">
<label for="signin_username">Username:</label>
<input ng-model="username" type="text" name="username" id="signin_username" placeholder="Enter Username" class="my-form-control" required username>
<div ng-show="signin_form.$submitted || signin_form.username.$touched">
<div ng-show="signin_form.username.$error.required">Tell us your username. </div>
</div>
</div>
</form>
</div>
Here is my custom validation:
var app = angular.module('custom_validation');
var helper = require('../helper.js')
app.directive('username', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.username = function(modelValue, viewValue) {
if (ctrl.$isEmpty(modelValue)) {
return false; //required
}
var msg = helper.validation.username(username)
if (msg)
return false
return true
};
}
};
});
Notice that my validation.js file also handles required, so I would like to use only my custom_validation. But it can only return true false value. How can I pass along the error message?
I will probably be using ng-message like
<div ng-message="required">You did not enter a field</div>
But the error message is still not from my validation.js
The reason I want to encapsulate validation is that,
the UI implementor should not worry about if a field is required or not, for example. It should be as simple as checking an input and getting the error message.
Also, The file is reused in my server code, for example (Server mongodb code)
UserSchema.pre('save', true, function(next, done) {
var self = this //in case inside a callback
var msg = helper.validation.user.username(self.username)
if (msg) {
self.invalidate('username', msg)
done(helper.getValidationError(msg))
}
else
done()
next()
})
$watchthe input manuallybusiness logicand should be separated from the UI part.validation.jsis well encapsulated and the UI implementor should not worry about if a field isrequiredor not, for example.