Utilizing a template-driven strategy for constructing forms in Angular 2, I have successfully implemented custom validators that can be utilized within the template.
However, I am facing an issue with displaying specific error messages associated with distinct errors. I aim to identify the reason behind the form's invalidity. How can this be accomplished?
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Site } from './../site';
import { BackendService } from './../backend.service';
import { email } from './../validators';
import { CustomValidators } from './../validators';
@Component({
templateUrl: 'app/templates/form.component.html',
styleUrls: ['app/css/form.css'],
directives: [CustomValidators.Email, CustomValidators.Url, CustomValidators.Goof],
providers: [BackendService]
})
export class FormComponent {
active = true;
submitted = false;
model = new Site();
onSubmit() {
this.submitted = true;
console.log(this.model);
}
resetForm() {
this.model = new Site();
this.submitted = false;
this.active = false;
setTimeout(() => this.active = true, 0);
}
get diagnostics() {
return JSON.stringify(this.model)
}
}
import { Directive, forwardRef } from '@angular/core';
import { NG_VALIDATORS, FormControl } from '@angular/forms';
import { BackendService } from './backend.service';
function validateEmailFactory(backend:BackendService) {
return (c:FormControl) => {
let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
return EMAIL_REGEXP.test(c.value) ? null : {
validateEmail: {
valid: false
}
};
};
}
export module CustomValidators {
@Directive({
selector: '[email][ngModel],[email][formControl]',
providers: [
{provide: NG_VALIDATORS, useExisting: forwardRef(() => CustomValidators.Email), multi: true}
]
})
export class Email {
validator:Function;
constructor(backend:BackendService) {
this.validator = validateEmailFactory(backend);
}
validate(c:FormControl) {
return this.validator(c);
}
}
@Directive({
selector: '[url][ngModel],[url][formControl]',
providers: [
{provide: NG_VALIDATORS, useExisting: forwardRef(() => CustomValidators.Url), multi: true}
]
})
export class Url {
validator:Function;
constructor(backend:BackendService) {
this.validator = validateEmailFactory(backend);
}
validate(c:FormControl) {
var pattern = /(https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/;
return pattern.test(c.value) ? null : {
validateEmail: {
valid: false
}
};
}
}
@Directive({
selector: '[goof][ngModel],[goof][formControl]',
providers: [
{provide: NG_VALIDATORS, useExisting: forwardRef(() => CustomValidators.Goof), multi: true}
]
})
export class Goof {
validate(c:FormControl) {
return {
validateGoof: {
valid: false
}
};
}
}
}