Skip to content

Instantly share code, notes, and snippets.

@Vaccano
Created February 26, 2016 17:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vaccano/e532610df4bff3211eb1 to your computer and use it in GitHub Desktop.
Save Vaccano/e532610df4bff3211eb1 to your computer and use it in GitHub Desktop.
Masked Input for Aurelia using jquery.mask
import {inject, customAttribute, bindable, bindingMode} from 'aurelia-framework';
@customAttribute('input-mask')
@inject(Element)
export class InputMaskCustomAttribute {
@bindable({ defaultBindingMode: bindingMode.twoWay, changeHandler: 'onUnmaskedValueChanged' })
unmaskedValue: any;
onUnmaskedValueChanged(newValue, oldValue) {
console.log('unmaskedValue updated from inside the custom attribute');
}
@bindable
mask: string;
element: HTMLInputElement;
isValidInputElement: boolean;
// The maskedinput jquery pluggin does not allow the events that aurelia needs
// for binding to get through. So we will manually put them through.
// This is the list of events we are going to look for. "focusout" allows for the value
// to be correct intime for "onblur".
aureliaBindEvents: string = 'focusout';
eventTarget: JQuery = undefined;
constructor(element) {
if (element instanceof HTMLInputElement) {
this.element = element;
this.isValidInputElement = true;
} else
this.isValidInputElement = false;
}
attached() {
this.setupMask(this.mask);
}
detached() {
this.tearDownMask();
}
maskChanged(newValue, oldValue) {
this.tearDownMask();
this.setupMask(newValue);
}
setupMask(mask: string) {
if (this.isValidInputElement && mask) {
this.eventTarget = (<any>$(this.element)).mask(this.mask, <any>{
translation: {
// Used for user entered boxes
'1': {
pattern: /[1-6]/,
optional: false
},
// Used for system assinged boxes
'7': {
pattern: /[7-9]/,
optional: false
},
// Used for airbill
'Z': {
pattern: /[a-zA-Z0-9]/,
optional: true
},
},
clearIfNotMatch: true
});
this.eventTarget.on(this.aureliaBindEvents, (e: any) => {
//this.unmasked((<any>$(this.element)).cleanVal());
this.unmaskedValue = (<any>$(this.element)).cleanVal()
this.fireEvent(e.target, 'input');
});
}
}
tearDownMask() {
if (this.isValidInputElement) {
if (this.eventTarget) {
this.eventTarget.off(this.aureliaBindEvents);
}
(<any>$(this.element)).unmask();
}
}
createEvent(name: string) {
let event = document.createEvent('Event');
event.initEvent(name, true, true);
return event;
}
fireEvent(element: HTMLElement, name: string) {
var event = this.createEvent(name);
element.dispatchEvent(event);
}
}
@cosmoKenney
Copy link

Great work! I was able to adapt this to jquery.maskedinput.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment