-
Notifications
You must be signed in to change notification settings - Fork 1
402 Validation Message
When the user enters a name of a hero that already exists the ngModel becomes invalid. As it is invalid the input get's a red border and the save button is disabled.
To give the user a visual feedback why the input is invalid we add a validation message for our custom validator.
The mw-input-wrapper
is responsible to show the respective error message for all ngModel
errors.
For the common errors like min-length
, max-length
, min
, max
, url
, email
, pattern
the mw-uikit
provides already the according messages.
For our custom validator we have to register a new validation message.
Open the directive hero-validate-unique.directive.js
that you created in the previous step.
We add a config block there that configures our message for the ngModel
error heroUnique
angular.module('mwPortal.Hero')
.config(function(mwValidationMessagesProvider){
mwValidationMessagesProvider.registerValidator(
'heroUnique', // name of the validator for which you want to provide a text message
'hero.validators.notUnique' //string to you i18n resource that will be used by i18n
);
})
.directive('heroValidateUnique', function (HeroesCollection) {...}
Normally the config blocks belong in the module "main" file but in this case we put it here because it belongs to the directive below and makes it easier to find.
When the hero name already exist the our heroUnique
validator will return false and therefore the ngModel has the error heroUnique
.
We provide a text for the heroUnique
error by registering a validator at the mwValidationMessagesProvider
.
The mw-input-wrapper
looks through all ngModel
errors and check if mwValidationMessage
has a message for that error.
Instead of The hero does already exist
we want to have a message like The hero with the name "xyz" does already exist
.
The mwValidationMessages can also handle this case. You can update each registered validation message during runtime.
To do so we inject i18n
and mwValidationMessages
into our directive.
...
.directive('heroValidateUnique', function (mwValidationMessages, i18n, HeroesCollection) {...}
Now we can update our message by setting a new message where we can provide the name of the entered hero
ngModel.$validators.heroUnique = function (value) {
...
if(existingHero){
//We update the existing validation message so can display the name of the already existing hero
mwValidationMessages.updateMessage(
'heroUnique', // name of the validator for which we want to update the message
function(){
return i18n.get('hero.validators.notUnique', {name: value}); // value is the name that the user has entered
}
);
}
...
}
Open the file en_US.json
in the folder hero/i18n
and add the following
"hero": {
"validators": {
"notUnique": "The hero with the name \"{{name}}\" does already exist"
}
}
and for de_DE.json
"hero": {
"validators": {
"notUnique": "Der Held mit dem Namen \"{{name}}\" existiert bereits"
}
}