Skip to content

Instantly share code, notes, and snippets.

@olaferlandsen
Last active October 20, 2017 13:24
Show Gist options
  • Save olaferlandsen/560a7177e0c2a0bb34000947856d05c1 to your computer and use it in GitHub Desktop.
Save olaferlandsen/560a7177e0c2a0bb34000947856d05c1 to your computer and use it in GitHub Desktop.
Directiva para formatear RUT en Ionic2
@NgModule({
declarations: [
//...
IonRutDirective
//...
]
})
<form>
<ion-input type="text" placeholder="Escriba su RUT aquí..." ion-rut>
</form>
import {Directive, ElementRef, HostListener, Input} from '@angular/core';
@Directive({
selector: '[ion-rut]',
host : {
'(focus)' : 'onFocus',
'(blur)' : 'onBlur'
}
})
export class IonRutDirective {
@Input() name : string;
@Input() value : string;
constructor(public element : ElementRef) {}
public validate (full:any) {
if (typeof full == "number") full = (<number>full).toString();
else if (typeof full !== "string") full = "";
full = full.replace(/([^0-9kK\-]+)/g, '');
if (!/^[0-9]+[-|‐]{1}[0-9k]{1}$/.test( full )) return false;
let tmp = full.split('-');
let dv:Function = (T:any) => {
let M=0,S=1;
for(;T;T=Math.floor(T/10)) S=(S+T%10*(9-M++%6))%11;
return S?S-1:'k';
};
return (dv(tmp[0]) == tmp[1]);
}
public format (value:string) {
value = typeof value === 'string' ? value.replace(/[^0-9kK]+/g, '').toUpperCase() : '';
if (value.length <= 1) return value;
let result: string = `${value.slice(-4, -1)}-${value.substr(value.length - 1)}`;
for (let i: number = 4; i < value.length; i += 3) result = `${value.slice(-3 - i, -i)}.${result}`;
return result;
}
public updateValidity () {
if (!this.validate(this.element.nativeElement.firstElementChild.value)) {
this.element.nativeElement.classList.add('ng-invalid');
this.element.nativeElement.firstElementChild.classList.add('ng-invalid');
}
else {
this.element.nativeElement.classList.remove('ng-invalid');
this.element.nativeElement.firstElementChild.classList.remove('ng-invalid');
}
}
@HostListener('blur') onBlur () {
let element = this.element.nativeElement.firstElementChild;
this.updateValidity();
element.value = this.format(element.value);
}
@HostListener('focus') public onFocus () {
let element = this.element.nativeElement.firstElementChild;
this.updateValidity();
element.value = this.format(element.value);
}
@HostListener('input') public onInput () {
let element = this.element.nativeElement.firstElementChild;
this.updateValidity();
element.value = this.format(element.value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment