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>
Top comments (1)
Hello. If you are still looking for solution of max and min length of angular form then let's discuss about it further. Please drop me a message at
grdtechlab@gmail.com
Feel free to connect. Thanks.