Phone serialization

In this example we're creating input for phone number that starts with +1 or +4. Property createHiddenInput tells tformat to create a hidden input that stores unformatted phone number for form. Unformatted value can be shown by pressing button.

new TemplateFormatter(
    'phoneInput', 
    {
        template: '+1 (xxx) xxx xx xx',
        createHiddenInput: true,
        prefixes: ["+4 ("],
        showTemplateOnFocus: true,
        emptySpaceChar: '_'        
    });

Handle input change

In this example we're using tformat onchange event to show card payment system. American Express cards starts with 3 (it's the first template prefix), VISA cards starts with 4 (it's the second template prefix) and so on.

Acceptable cards:

  • American Express
  • VISA
  • Mastercard
function highlightCardType(cardType) {
    creditCardList = document.getElementById('creditCardList');

    creditCardList.querySelectorAll('li').forEach(t => {
        t.classList.remove('clr-valid');
        if (t.dataset['cardType'] == cardType)
            t.classList.add('clr-valid');
    })
    
    if (cardType == -1)
        creditCardList.classList.remove('faded');
    else
        creditCardList.classList.add('faded');
}

let cardInput = document.getElementById('cardInput');
/* We can also initialize formatter with HTMLElement */                
emplateFormatter(cardInput, {
    template: "3xxx xxxx xxxx",
    prefixes: ["4", "5"]
});

cardInput.addEventListener('tf.p.onchange', function (e) {
    let enteredCardType = e.detail;

    highlightCardType(enteredCardType);
});

Multiple templates

In this example we're using multiple templates. If user selects "Phone number" from dropdown then template will be changed to +1 xxx xxx xx xx.

Find parcel by  
const parcelCodeTemplate = "LCxxxxxxCN";
const phoneNumberTemplate = "+1 xxx xxx xx xx";
let parcelFormatter = new TemplateFormatter('postInput', {
    template: parcelCodeTemplate
})
parcelFormatter._inputElement.setAttribute('placeholder', parcelCodeTemplate);

document.getElementById("postInputType").addEventListener('change', (e) => {
    switch (e.target.value) {
        case "1":
            parcelFormatter.template = parcelCodeTemplate;
            parcelFormatter._inputElement.setAttribute('placeholder', parcelCodeTemplate);
            parcelFormatter._inputElement.value = '';
            break;
        case "2":
            parcelFormatter.template = phoneNumberTemplate;
            parcelFormatter._inputElement.setAttribute('placeholder', phoneNumberTemplate);
            parcelFormatter._inputElement.value = '';
            break;
    }
})