File

projects/common/lib/components/sin/sin.component.ts

Description

This component reports the following errors. required invalid duplicate

These messages can be changed by updated messages using the errorMessages interface Ex. { required: 'This field is required', invalid: '{label} is invalid' }

Extends

AbstractFormControl

Implements

OnInit

Metadata

selector common-sin
styleUrls ./sin.component.scss
templateUrl ./sin.component.html

Index

Properties
Methods
Inputs
Outputs
Accessors

Constructor

constructor(controlDir: NgControl)
Parameters :
Name Type Optional
controlDir NgControl No

Inputs

label
Type : string
Default value : 'Social Insurance Number (SIN)'
labelforId
Type : string
Default value : 'sin_' + this.objectId
maxlength
Type : string
Default value : '15'
placeholder
Type : string
Default value : '111 111 111'
value
Type : string
disabled
Type : boolean
Default value : false
Inherited from AbstractFormControl
errorMessage
Type : ErrorMessage
Inherited from AbstractFormControl
label
Type : string
Inherited from AbstractFormControl

Outputs

blur
Type : EventEmitter<any>
valueChange
Type : EventEmitter<string>

Methods

ngOnInit
ngOnInit()
Returns : void
onBlur
onBlur(event: any)
Parameters :
Name Type Optional
event any No
Returns : void
onValueChange
onValueChange(value: any)
Parameters :
Name Type Optional
value any No
Returns : void
Private validateSelf
validateSelf()
Returns : ValidationErrors | null
Private validateSin
validateSin()
Returns : ValidationErrors | null
writeValue
writeValue(value: any)
Parameters :
Name Type Optional
value any No
Returns : void
ngOnInit
ngOnInit()
Inherited from AbstractFormControl
Returns : void
registerOnChange
registerOnChange(fn: any)
Inherited from AbstractFormControl
Parameters :
Name Type Optional
fn any No
Returns : void
registerOnTouched
registerOnTouched(fn: any)
Inherited from AbstractFormControl
Parameters :
Name Type Optional
fn any No
Returns : void
Protected registerValidation
registerValidation(ngControl: NgControl, fn: ValidationErrors)
Inherited from AbstractFormControl

Register self validating method

Parameters :
Name Type Optional Description
ngControl NgControl No
fn ValidationErrors No

function for validating self

Returns : any
setDisabledState
setDisabledState(isDisabled: boolean)
Inherited from AbstractFormControl
Parameters :
Name Type Optional
isDisabled boolean No
Returns : void
Protected setErrorMsg
setErrorMsg()
Inherited from AbstractFormControl
Returns : void
Private validateLabel
validateLabel()
Inherited from AbstractFormControl
Returns : void
Abstract writeValue
writeValue(value: any)
Inherited from AbstractFormControl
Parameters :
Name Type Optional
value any No
Returns : void

Properties

_defaultErrMsg
Type : ErrorMessage
Default value : { required: `${LabelReplacementTag} is required.`, invalid: `${LabelReplacementTag} is invalid.`, duplicate: `${LabelReplacementTag} was already used for another family member.` }
Public controlDir
Type : NgControl
Decorators :
@Optional()
@Self()
mask
Type : any
sin
Type : string
Default value : ''
Abstract _defaultErrMsg
Type : ErrorMessage
Default value : {}
Inherited from AbstractFormControl
_onChange
Default value : () => {...}
Inherited from AbstractFormControl
_onTouched
Default value : () => {...}
Inherited from AbstractFormControl
Public objectId
Type : string
Default value : UUID.UUID()
Inherited from Base
Defined in Base:11

An identifier for parents to keep track of components

Accessors

value
getvalue()
setvalue(val: string)
Parameters :
Name Type Optional
val string No
Returns : void
import { Component, EventEmitter, Input, Output, Optional, Self, OnInit} from '@angular/core';
import { NUMBER, SPACE } from '../../models/mask.constants';
import { NgControl, ValidationErrors } from '@angular/forms';
import { AbstractFormControl } from '../../models/abstract-form-control';
import { LabelReplacementTag, ErrorMessage } from '../../models/error-message.interface';

/**
 * This component reports the following errors.
 *    required
 *    invalid
 *    duplicate
 *
 *  These messages can be changed by updated messages using the errorMessages interface
 *  Ex. { required: 'This field is required', invalid: '{label} is invalid' }
 */

@Component({
  selector: 'common-sin',
  templateUrl: './sin.component.html',
  styleUrls: ['./sin.component.scss']
})
export class SinComponent extends AbstractFormControl implements OnInit {

  _defaultErrMsg: ErrorMessage = {
    required: `${LabelReplacementTag} is required.`,
    invalid: `${LabelReplacementTag} is invalid.`,
    duplicate: `${LabelReplacementTag} was already used for another family member.`
  };

  sin: string = '';
  mask: any;

  @Input() label: string = 'Social Insurance Number (SIN)';
  @Input() maxlength: string = '15';
  @Input() placeholder: string = '111 111 111';
  @Input() labelforId: string = 'sin_' + this.objectId;

  @Input()
  set value( val: string ) {
    if ( val ) {
      this.sin = val;
    }
  }
  get value() {
    return this.sin;
  }

  @Output() valueChange: EventEmitter<string> = new EventEmitter<string>();
  @Output() blur: EventEmitter<any> = new EventEmitter<any>();

  constructor( @Optional() @Self() public controlDir: NgControl ) {
    super();
    if ( controlDir ) {
      controlDir.valueAccessor = this;
    }

    this.mask =
    [NUMBER, NUMBER, NUMBER, SPACE, NUMBER, NUMBER, NUMBER, SPACE, NUMBER, NUMBER, NUMBER];
  }

  ngOnInit() {
    super.ngOnInit();

    this.registerValidation( this.controlDir, this.validateSelf );
  }

  onValueChange( value: any ) {

    if ( value !== this.sin ) { // IE fix when focus does not display required error
      this.sin = value;
      this._onChange( value );
      this.valueChange.emit( value );
    }
  }

  onBlur( event: any ) {
    this._onTouched( event );
    this.blur.emit( event );
  }

  writeValue( value: any ): void {
    if ( value ) {
      this.sin = value;
    }
  }

  private validateSelf(): ValidationErrors | null {

    const validateResult = this.validateSin();
    if ( validateResult ) {
      return validateResult;
    }
    return null;
   }

   private validateSin(): ValidationErrors | null {

    if ( this.sin && this.sin.trim().length > 0 ) {

      // Init weights and other stuff
      const weights: number[] = [1, 2, 1, 2, 1, 2, 1, 2, 1];
      let sum = 0;

      // Clean up string
      const value = this.sin.trim();
      this.sin = value
                  .replace(/_/g, '') // remove underlines
                  .replace(/\s/g, ''); // spaces

      // Test for length
      if (this.sin.length !== 9) {
        return { 'invalid': true };
      }

      // Test for string of zeros
      if ( this.sin === '000000000') {
        return { 'invalid': true };
      }

      // Test for SINs that begin with 0
      if (this.sin[0] === '0') {
        return { 'invalid': true };
      }

      // Walk through each character
      for (let i = 0; i < this.sin.length; i++) {

        // pull out char
        const char = this.sin.charAt(i);

        // parse the number
        const num = Number(char);
        if (Number.isNaN(num)) {
          return { 'invalid': true };
        }

        // multiply the value against the weight
        let result = num * weights[i];

        // If two digit result, substract 9
        if (result > 9) {
          result = result - 9;
        }

        // add it to our sum
        sum += result;
      }

      // The sum must be divisible by 10
      if (sum % 10 !== 0) {
        return { 'invalid': true };
      }

    }

    return null;
  }
}

<label for="{{labelforId}}" class="control-label">{{label}}</label>
<input class="form-control"
       spellcheck="false"
       id="{{labelforId}}"
       [ngModel]="sin"
       (ngModelChange)="onValueChange($event)"
       (blur)="onBlur($event)"
       [placeholder]="placeholder"
       [textMask]="{mask: mask}"
       [disabled]="disabled"
       [maxlength]="maxlength"
       autocomplete="off"/>


  <!-- Error messages for input -->
  <common-error-container
      [displayError]="controlDir && !disabled && (controlDir.touched || controlDir.dirty) && controlDir.errors">
    <div *ngIf="controlDir.errors?.required">
      {{_defaultErrMsg.required}}
    </div>
    <div *ngIf="controlDir.errors?.invalid">
      {{_defaultErrMsg.invalid}}
    </div>
    <div *ngIf="controlDir.errors?.duplicate">
      {{_defaultErrMsg.duplicate}}
    </div>
  </common-error-container>

Legend
Html element
Component
Html element with directive

result-matching ""

    No results matching ""