Angular Dynamic Form Validators: minLength and maxLength Not Working
Prasad Lokhande
Posted on August 4, 2024
Issue Description
I am working on an Angular project to generate dynamic forms based on a JSON configuration. The forms can include input fields, groups (which can be a group of input fields), and lists (arrays of objects). I am facing an issue with validation. While the validation functions for required and pattern are working correctly, the validation functions for minLength and maxLength are not working.
Code
Validator Mapping Function
mapValidators(validators: any[]): { validators: any[], messages: any[] } {
const formValidators: any[] = [];
const messages: any[] = [];
if (validators) {
validators.forEach((validator) => {
switch (validator.type) {
case 'required':
formValidators.push(Validators.required);
messages.push(validator.message);
break;
case 'pattern':
formValidators.push(Validators.pattern(validator.pattern));
messages.push(validator.message);
break;
case 'minLength':
formValidators.push(Validators.minLength(validator.length));
messages.push(validator.message || `Minimum length is ${validator.length}`);
break;
case 'maxLength':
formValidators.push(Validators.maxLength(validator.length));
messages.push(validator.message || `Maximum length is ${validator.length}`);
break;
case 'custom':
// Assuming the custom validator is a function
formValidators.push(validator.validator);
messages.push(validator.message);
break;
}
});
}
return { validators: formValidators, messages: messages };
}
Display Error in Template
<div *ngSwitchCase="'String'" class="m-3">
<label for="{{ control.name }}" class="form-label">
{{ control.label }}
</label>
<input
id="{{ control.name }}"
type="text"
class="form-control custom-input-height custom-input-style"
[formControlName]="control.name"
placeholder="{{ control.placeholder || '' }}"
/>
<div
*ngIf="form.get(control.name)?.touched && form.get(control.name)?.invalid"
class="text-danger mt-1"
>
<div *ngFor="let validator of control.validators">
<div *ngIf="form.get(control.name)?.errors?.[validator.type]">
{{ validator.message }}
</div>
</div>
</div>
</div>
💖 💪 🙅 🚩
Prasad Lokhande
Posted on August 4, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.