I have a Lightning Input that when a user types into I would like it to be reformatted to mirror CC Credit Card formatting. For example when I type in 1234567812345678 it updates as the user is typing to 1234-5678-1234-5678. I have a function that is able to reformat the a value to represent this formatting. I am having an issue displaying the newly formatted value.
HTML
<div onkeyup={anKeyUp}>
<lightning-layout multiple-rows="false" vertical-align="end">
<lightning-layout-item size="12" small-device-size="10" medium-device-size="8"
large-device-size="6" padding="around-small">
<div class="slds-form-element">
<div class="slds-form-element__control">
<lightning-input type="search" label="Account Number" onchange={handleSearchTerm}
data-id="ANS" value={cardNumberFormating}>
</lightning-input>
</div>
</div>
</lightning-layout-item>
<lightning-layout-item size="12" small-device-size="2" medium-device-size="2"
large-device-size="2" padding="around-small">
<lightning-button label="Search" variant="brand" onclick={handleCMSearch}>
</lightning-button>
</lightning-layout-item>
</lightning-layout>
</div>
When the search term is changed it calls a "handleSearchTerm" Js. This is used to capture the value that will be used for the actual search. Within this JS I am calling my reformatting function and then attempting to display the new reformatted value onto the input.
JS
@track cardNumberFormating = '';
strSearchTerm = '';
// Search Term Handler
handleSearchTerm(event) {
console.log('Handling Search Term Update...');
this.strSearchTerm = event.detail.value;
console.log('Search Term: ', event.detail.value);
this.reformat(this.strSearchTerm);
}
// Reformating Functionality
reformat(value){
// Goal to reformat card search func to look like CC format xxxx-xxxx-xxxx-xxxx
console.log(value);
var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
var matches = v.match(/\d{4,16}/g);
var match = matches && matches[0] || ''
var parts = []
for (i=0, len=match.length; i<len; i+=4) {
parts.push(match.substring(i, i+4))
}
if (parts.length) {
return parts.join(' ')
} else {
this.cardNumberFormating = value;
}
}
I am getting a very generic error when typing into the search bar and it looks like its failing on the return of the reformat function.
Solution/Resolution:
// Reformating Functionality
reformat(value){
// Goal to reformat card search func to look like CC format xxxx-xxxx-xxxx-xxxx
console.log(value);
var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '');
var matches = v.match(/\d{4,16}/g);
var match = matches && matches[0] || '';
var parts = [];
var i;
for (i=0; i<match.length; i+=4) {
parts.push(match.substring(i, i+4))
}
if(parts.length) {
this.cardNumberFormating = parts.join('-');
} else {
this.cardNumberFormating = value;
}
console.log('Formatted Card Number: ', this.cardNumberFormating);
}