Guest User

Untitled

a guest
Jan 24th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.19 KB | None | 0 0
  1. import { Component, OnInit, Input, ChangeDetectionStrategy } from '@angular/core';
  2. import { FormGroup, ValidationErrors } from '@angular/forms';
  3.  
  4. @Component({
  5. selector: 'validation-errors',
  6. templateUrl: './validation-errors.component.html',
  7. styleUrls: ['./validation-errors.component.css'],
  8. changeDetection: ChangeDetectionStrategy.OnPush
  9. })
  10. export class ValidationErrorsComponent implements OnInit {
  11. @Input() errors: ValidationErrors;
  12.  
  13. constructor() {}
  14.  
  15. ngOnInit() {}
  16.  
  17. }
  18.  
  19. <ng-container *ngIf="errors && errors['required']"> Required</ng-container>
  20. <ng-container *ngIf="errors && errors['notUnique']">Already exists</ng-container>
  21. <ng-container *ngIf="errors && errors['email']">Please enter a valid email</ng-container>
  22.  
  23. const nameControl = this.userForm.get('name');
  24. nameControl.setErrors({
  25. "notUnique": true
  26. });
  27.  
  28. <form [formGroup]="userForm" (ngSubmit)="submit()">
  29. <mat-form-field>
  30. <input matInput placeholder="name" formControlName="name" required>
  31. <mat-error *ngIf="userForm.get('name').status === 'INVALID'">
  32. <validation-errors [errors]="userForm.get('name').errors"></validation-errors>
  33. </mat-error>
  34. </mat-form-field>
  35. <mat-form-field>
  36. <input matInput placeholder="email" formControlName="email" required>
  37. <mat-error *ngIf="userForm.get('email').status === 'INVALID'">
  38. <validation-errors [errors]="userForm.get('email').errors"></validation-errors>
  39. </mat-error>
  40. </mat-form-field>
  41. <button mat-raised-button class="mat-raised-button" color="accent">SUBMIT</button>
  42. </form>
  43.  
  44. @Component({
  45. selector: '[validator]',
  46. template: `
  47. <ng-content></ng-content>
  48. <div *ngIf="formControl.invalid">
  49. <div *ngIf="formControl.errors.required && (form.submitted || formControl.dirty)">
  50. Please provide {{ formControl.name }}
  51. </div>
  52. <div *ngIf="formControl.errors.email && (form.submitted || formControl.dirty)">
  53. Please provide a valid email
  54. </div>
  55. <div *ngIf="formControl.errors.notstring && (form.submitted || formControl.dirty)">
  56. Invalid name
  57. </div>
  58.  
  59. </div>
  60. `})
  61.  
  62. export class ValidatorComponent implements OnInit {
  63. @ContentChild(FormControlName) formControl;
  64. constructor(private form: NgForm) {
  65.  
  66. }
  67.  
  68. ngOnInit() { }
  69.  
  70. }
  71.  
  72. <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
  73. <div [formGroup]="myForm">
  74. <label>Name</label>
  75. <div validator>
  76. <input type="text" formControlName="name">
  77. </div>
  78. <label>Lastname</label>
  79. <div validator>
  80. <input type="text" formControlName="lastname">
  81. </div>
  82. <label>Email</label>
  83. <div validator>
  84. <input type="text" formControlName="email">
  85. </div>
  86. </div>
  87. <button type="submit">Submit</button>
  88. </form>
  89.  
  90. [{
  91. "nameType" : {
  92. maxLength : 5 ,
  93. minLength : 1 ,
  94. pattern : xxxxxx,
  95. etc
  96. etc
  97.  
  98. }
  99. }
  100. ]
  101.  
  102. <p class="error_message" *ngIf="form.get(controlName).hasError('required') && (form.submitted || form.get(controlName).dirty)">Please provide {{controlName}}</p>
  103. <p class="error_message" *ngIf="form.get(controlName).hasError('email') && (form.submitted || form.get(controlName).dirty)">Please provide valid {{controlName}}</p>
  104. ...other errors
  105.  
  106. @Input() controlName;
  107. @Input() form;
  108.  
  109. <validation-messages [form]="myForm" controlName="email"></validation-messages>
  110.  
  111. <div *ngIf="this.formControl.errors">
  112. <p>this.formControl.errors?.message</p>
  113. </div>
  114.  
  115. <form [formGroup]="editorForm" novalidate>
  116. <label>First Name</label>
  117. <input formControlName="firstName" type="text">
  118. <ng2-mdf-validation-message [control]="firstName" *ngIf="!firstName.pristine"></ng2-mdf-validation-message>
  119. </form>
  120.  
  121. @Directive(...)
  122. export class ValidatorMessageDirective implements OnInit {
  123.  
  124. constructor(
  125. private container: ControlContainer,
  126. private elem: ElementRef, // host dom element
  127. private control: NgControl // host form control
  128. ) { }
  129.  
  130. ngOnInit() {
  131. const control = this.control.control;
  132.  
  133. control.valueChanges.pipe(distinctUntilChanged()).subscribe(() => {
  134. this.option.forEach(validate => {
  135. if (control.hasError(validate.type)) {
  136. const validateMessageElem = document.getElementById(validate.id);
  137. if (!validateMessageElem) {
  138. const divElem = document.createElement('div');
  139. divElem.innerHTML = validate.message;
  140. divElem.id = validate.id;
  141. this.elem.nativeElement.parentNode.insertBefore(divElem, this.elem.nativeElement.nextSibling);
  142. }
  143. } else {
  144. const validateMessageElem = document.getElementById(validate.id);
  145. if (validateMessageElem) {
  146. this.elem.nativeElement.parentNode.removeChild(validateMessageElem);
  147. }
  148. }
  149. })
  150. });
  151. }
  152. }
  153.  
  154. <form [formGroup]="form">
  155. <input type="text" formControlName="test" [validate-message]="testValidateOption"><br/>
  156. <input type="number" formControlName="test2" [validate-message]="test2ValidateOption">
  157. </form>
  158.  
  159. <div class="input" [caption]="'SSN: '" name="ssn" type="text" [(ngModel)]="item.ssn" [async]="memberSsnValidatorFn" required></div>
  160.  
  161. import { AbstractControl } from "@angular/forms";
  162.  
  163. type ErrorFunction = (errorName: string, error: object) => string;
  164. export type ErrorGetter =
  165. string | { [key2: string]: string } | ErrorFunction;
  166.  
  167. export class FormError {
  168. constructor(private errorGetter?: ErrorGetter) { }
  169. hasError(abstractControl: AbstractControl) {
  170. return abstractControl.errors && (abstractControl.dirty || abstractControl.touched);
  171. }
  172. getErrorMsgs(abstractControl: AbstractControl): string[] {
  173. if (!this.hasError(abstractControl))
  174. return null;
  175. let errors = abstractControl.errors;
  176. return Object.keys(errors).map(anyError => this.getErrorValue(anyError, errors[anyError]));
  177. }
  178. getErrorValue(errorName: string, error: object): string {
  179. let errorGetter = this.errorGetter;
  180. if (!errorGetter)
  181. return predictError(errorName, error);
  182. if (isString(errorGetter))
  183. return errorGetter;
  184. else if (isErrorFunction(errorGetter)) {
  185. let errorString = errorGetter(errorName, error);
  186. return this.predictedErrorIfEmpty(errorString, errorName, error)
  187. }
  188. else {
  189. let errorString = this.errorGetter[errorName];
  190. return this.predictedErrorIfEmpty(errorString, errorName, error)
  191. }
  192. }
  193. predictedErrorIfEmpty(errorString: string, errorName: string, error: object) {
  194. if (errorString == null || errorString == undefined)
  195. return predictError(errorName, error);
  196. return errorString;
  197. }
  198.  
  199.  
  200. }
  201. function predictError(errorName: string, error: object): string {
  202. if (errorName === 'required')
  203. return 'Cannot be blank';
  204. if (errorName === 'min')
  205. return `Should not be less than ${error['min']}`;
  206. if (errorName === 'max')
  207. return `Should not be more than ${error['max']}`;
  208. if (errorName === 'minlength')
  209. return `Alteast ${error['requiredLength']} characters`;
  210. if (errorName === 'maxlength')
  211. return `Atmost ${error['requiredLength']} characters`;
  212. // console.warn(`Error for ${errorName} not found. Error object = ${error}`);
  213. return 'Error';
  214. }
  215. export function isString(s: any): s is string {
  216. return typeof s === 'string' || s instanceof String;
  217. }
  218. export function isErrorFunction(f: any): f is ErrorFunction {
  219. return typeof f === "function";
  220. }
  221.  
  222. class FormError {
  223. constructor(private errorGetter?: ErrorGetter) { }
  224. }
  225.  
  226. type ErrorFunction = (errorName: string, error: object) => string;
  227. type ErrorGetter =
  228. string | { [key2: string]: string } | ErrorFunction;
  229.  
  230. <ng-container *ngIf="formError.hasError(control)">
  231. <div class='form-error-message' *ngFor='let error of formError.getErrorMsgs(control)'>{{error}}</div>
  232. </ng-container>
  233.  
  234. form-error {
  235. .form-error-message {
  236. color: red;
  237. font-size: .75em;
  238. padding-left: 16px;
  239. }
  240. }
  241.  
  242. @Component({
  243. selector: 'form-error',
  244. templateUrl: 'form-error.html'
  245. })
  246. export class FormErrorComponent {
  247. @Input() formError: FromError;
  248. @Input() control: AbstractControl;
  249. }
  250.  
  251. <form-error [control]='thatControl' ></form-error>
Add Comment
Please, Sign In to add comment