Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Component, OnInit, Input, ChangeDetectionStrategy } from '@angular/core';
- import { FormGroup, ValidationErrors } from '@angular/forms';
- @Component({
- selector: 'validation-errors',
- templateUrl: './validation-errors.component.html',
- styleUrls: ['./validation-errors.component.css'],
- changeDetection: ChangeDetectionStrategy.OnPush
- })
- export class ValidationErrorsComponent implements OnInit {
- @Input() errors: ValidationErrors;
- constructor() {}
- ngOnInit() {}
- }
- <ng-container *ngIf="errors && errors['required']"> Required</ng-container>
- <ng-container *ngIf="errors && errors['notUnique']">Already exists</ng-container>
- <ng-container *ngIf="errors && errors['email']">Please enter a valid email</ng-container>
- const nameControl = this.userForm.get('name');
- nameControl.setErrors({
- "notUnique": true
- });
- <form [formGroup]="userForm" (ngSubmit)="submit()">
- <mat-form-field>
- <input matInput placeholder="name" formControlName="name" required>
- <mat-error *ngIf="userForm.get('name').status === 'INVALID'">
- <validation-errors [errors]="userForm.get('name').errors"></validation-errors>
- </mat-error>
- </mat-form-field>
- <mat-form-field>
- <input matInput placeholder="email" formControlName="email" required>
- <mat-error *ngIf="userForm.get('email').status === 'INVALID'">
- <validation-errors [errors]="userForm.get('email').errors"></validation-errors>
- </mat-error>
- </mat-form-field>
- <button mat-raised-button class="mat-raised-button" color="accent">SUBMIT</button>
- </form>
- @Component({
- selector: '[validator]',
- template: `
- <ng-content></ng-content>
- <div *ngIf="formControl.invalid">
- <div *ngIf="formControl.errors.required && (form.submitted || formControl.dirty)">
- Please provide {{ formControl.name }}
- </div>
- <div *ngIf="formControl.errors.email && (form.submitted || formControl.dirty)">
- Please provide a valid email
- </div>
- <div *ngIf="formControl.errors.notstring && (form.submitted || formControl.dirty)">
- Invalid name
- </div>
- </div>
- `})
- export class ValidatorComponent implements OnInit {
- @ContentChild(FormControlName) formControl;
- constructor(private form: NgForm) {
- }
- ngOnInit() { }
- }
- <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
- <div [formGroup]="myForm">
- <label>Name</label>
- <div validator>
- <input type="text" formControlName="name">
- </div>
- <label>Lastname</label>
- <div validator>
- <input type="text" formControlName="lastname">
- </div>
- <label>Email</label>
- <div validator>
- <input type="text" formControlName="email">
- </div>
- </div>
- <button type="submit">Submit</button>
- </form>
- [{
- "nameType" : {
- maxLength : 5 ,
- minLength : 1 ,
- pattern : xxxxxx,
- etc
- etc
- }
- }
- ]
- <p class="error_message" *ngIf="form.get(controlName).hasError('required') && (form.submitted || form.get(controlName).dirty)">Please provide {{controlName}}</p>
- <p class="error_message" *ngIf="form.get(controlName).hasError('email') && (form.submitted || form.get(controlName).dirty)">Please provide valid {{controlName}}</p>
- ...other errors
- @Input() controlName;
- @Input() form;
- <validation-messages [form]="myForm" controlName="email"></validation-messages>
- <div *ngIf="this.formControl.errors">
- <p>this.formControl.errors?.message</p>
- </div>
- <form [formGroup]="editorForm" novalidate>
- <label>First Name</label>
- <input formControlName="firstName" type="text">
- <ng2-mdf-validation-message [control]="firstName" *ngIf="!firstName.pristine"></ng2-mdf-validation-message>
- </form>
- @Directive(...)
- export class ValidatorMessageDirective implements OnInit {
- constructor(
- private container: ControlContainer,
- private elem: ElementRef, // host dom element
- private control: NgControl // host form control
- ) { }
- ngOnInit() {
- const control = this.control.control;
- control.valueChanges.pipe(distinctUntilChanged()).subscribe(() => {
- this.option.forEach(validate => {
- if (control.hasError(validate.type)) {
- const validateMessageElem = document.getElementById(validate.id);
- if (!validateMessageElem) {
- const divElem = document.createElement('div');
- divElem.innerHTML = validate.message;
- divElem.id = validate.id;
- this.elem.nativeElement.parentNode.insertBefore(divElem, this.elem.nativeElement.nextSibling);
- }
- } else {
- const validateMessageElem = document.getElementById(validate.id);
- if (validateMessageElem) {
- this.elem.nativeElement.parentNode.removeChild(validateMessageElem);
- }
- }
- })
- });
- }
- }
- <form [formGroup]="form">
- <input type="text" formControlName="test" [validate-message]="testValidateOption"><br/>
- <input type="number" formControlName="test2" [validate-message]="test2ValidateOption">
- </form>
- <div class="input" [caption]="'SSN: '" name="ssn" type="text" [(ngModel)]="item.ssn" [async]="memberSsnValidatorFn" required></div>
- import { AbstractControl } from "@angular/forms";
- type ErrorFunction = (errorName: string, error: object) => string;
- export type ErrorGetter =
- string | { [key2: string]: string } | ErrorFunction;
- export class FormError {
- constructor(private errorGetter?: ErrorGetter) { }
- hasError(abstractControl: AbstractControl) {
- return abstractControl.errors && (abstractControl.dirty || abstractControl.touched);
- }
- getErrorMsgs(abstractControl: AbstractControl): string[] {
- if (!this.hasError(abstractControl))
- return null;
- let errors = abstractControl.errors;
- return Object.keys(errors).map(anyError => this.getErrorValue(anyError, errors[anyError]));
- }
- getErrorValue(errorName: string, error: object): string {
- let errorGetter = this.errorGetter;
- if (!errorGetter)
- return predictError(errorName, error);
- if (isString(errorGetter))
- return errorGetter;
- else if (isErrorFunction(errorGetter)) {
- let errorString = errorGetter(errorName, error);
- return this.predictedErrorIfEmpty(errorString, errorName, error)
- }
- else {
- let errorString = this.errorGetter[errorName];
- return this.predictedErrorIfEmpty(errorString, errorName, error)
- }
- }
- predictedErrorIfEmpty(errorString: string, errorName: string, error: object) {
- if (errorString == null || errorString == undefined)
- return predictError(errorName, error);
- return errorString;
- }
- }
- function predictError(errorName: string, error: object): string {
- if (errorName === 'required')
- return 'Cannot be blank';
- if (errorName === 'min')
- return `Should not be less than ${error['min']}`;
- if (errorName === 'max')
- return `Should not be more than ${error['max']}`;
- if (errorName === 'minlength')
- return `Alteast ${error['requiredLength']} characters`;
- if (errorName === 'maxlength')
- return `Atmost ${error['requiredLength']} characters`;
- // console.warn(`Error for ${errorName} not found. Error object = ${error}`);
- return 'Error';
- }
- export function isString(s: any): s is string {
- return typeof s === 'string' || s instanceof String;
- }
- export function isErrorFunction(f: any): f is ErrorFunction {
- return typeof f === "function";
- }
- class FormError {
- constructor(private errorGetter?: ErrorGetter) { }
- }
- type ErrorFunction = (errorName: string, error: object) => string;
- type ErrorGetter =
- string | { [key2: string]: string } | ErrorFunction;
- <ng-container *ngIf="formError.hasError(control)">
- <div class='form-error-message' *ngFor='let error of formError.getErrorMsgs(control)'>{{error}}</div>
- </ng-container>
- form-error {
- .form-error-message {
- color: red;
- font-size: .75em;
- padding-left: 16px;
- }
- }
- @Component({
- selector: 'form-error',
- templateUrl: 'form-error.html'
- })
- export class FormErrorComponent {
- @Input() formError: FromError;
- @Input() control: AbstractControl;
- }
- <form-error [control]='thatControl' ></form-error>
Add Comment
Please, Sign In to add comment