Reputation: 119
I am using angular formly-forms in a bunch of different HTML pages on my App. I am using validation as an example:
{
className: 'col-xs-5',
key: 'poc',
type: 'input',
templateOptions: {
type: 'text',
required: true,
label: 'Point of Contact',
maxlength: 15,
placeholder: "Enter Point of Contact's username"
},
validators:{
username:{
expression: function(viewValue, modelValue) {
var value = modelValue || viewValue;
return !value || /^\d*[a-zA-Z][a-zA-Z\d]*$/.test(value);
},
message: '$viewValue + " is not a valid username"'
},
},
I want to have this validation available on my other HTML forms as well without having to repeat the validator function. I have read that I could make a custom username type that perhaps has this validator logic & message build in? I am just again not sure how to make this global.
In my app.config.js I do have a couple global messages what work to display the error messages for the base angular-formly errors but not sure how to make it do that for my custom ones
formlyValidationMessages.addStringMessage('required', 'This field is required');
formlyValidationMessages.addStringMessage('maxlength', 'Input is too long!');
I cannot find a good example of someone succesfully doing this and would greatly appricate some help!
Upvotes: 2
Views: 1021
Reputation: 119
For anyone looking for how to do this in the future. Take a look at the example in this video. https://egghead.io/lessons/angularjs-angular-formly-default-options
In terms of how to do it for the example I outlined.
> angular.module('cim').run(function(formlyConfig,
> formlyValidationMessages) { formlyConfig.setType({
> name: 'username',
> defaultOptions: {
> templateOptions: {
> type: 'text',
> required: true,
> label: 'Point of Contact',
> maxlength: 15,
> placeholder: "Enter Point of Contact's username",
> },
> validators:{
> username:{
> expression: function(viewValue, modelValue) {
> var value = modelValue || viewValue;
> return !value || /^\d*[a-zA-Z][a-zA-Z\d]*$/.test(value);
> },
> message: '$viewValue + " is not a valid username"'
> },
> },
> }
Upvotes: 2