timofei-iatsenko / angular-cc-library

Library to support Credit Card input masking and validation
MIT License
82 stars 71 forks source link

Can't delete digits when cursor at end of numeric section #59

Open esoyke opened 4 years ago

esoyke commented 4 years ago

Say you have entered the value 2345 0000 0000 0000. If you position the cursor just after the 5, delete doesn't work (backspace always works fine). Delete only works when there is a number directly to the right of the cursor, not a space.

esoyke commented 4 years ago

I found a workaround that seems to work. In the safeVal() method in credit-card.ts, I advance the cursor by one if it's at the end of a 4 digit segment:

try {
    cursor = target.selectionStart;
    if(cursor==4 || cursor==9 || cursor==14 || cursor==19){
        cursor++;
    }
} catch (error) {}
esoyke commented 4 years ago

I refined it a little further to automatically delete the value to the right of the space, and also only do so if they hit the Delete key. In the reFormatCardNumber() method of credit-card-directive, I check if it's a Delete event:

if(e instanceof KeyboardEvent && e.code.toUpperCase()=='DELETE')
    deleteKey = true;

Pass that deleteKey flag as a new boolean input to safeVal(), then only if a delete was performed, advance the cursor and delete the digit past the space.

try {
    cursor = target.selectionStart;
    if(deleteKey && (cursor==4 || cursor==9 || cursor==14 || cursor==19)){
        cursor++;
        // simulate another delete event by removing the character the user would have indented to delete
        let  preDeleteSegment = value.substring(0, cursor);
        let  postDeleteSegment = value.substring(cursor+1, value.length);
        value = preDeleteSegment+postDeleteSegment;
    }
} catch (error) {}