Created
March 18, 2021 22:10
-
-
Save leastbad/2b16b1526ce87cd0fd1f09ebab370d45 to your computer and use it in GitHub Desktop.
Stimulus controller for cleave.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Controller } from 'stimulus' | |
import Cleave from 'cleave.js' | |
import 'cleave.js/dist/addons/cleave-phone.us' | |
export default class extends Controller { | |
static values = { options: Object, digits: Number } | |
connect () { | |
this.cleave = new Cleave(this.element, this.optionsValue) | |
if (this.hasDigitsValue) { | |
this.element.addEventListener('beforeinput', this.inputHandler) | |
this.element.addEventListener('paste', this.pasteHandler) | |
} | |
} | |
disconnect () { | |
this.cleave.destroy() | |
if (this.hasDigitsValue) { | |
this.element.removeEventListener('beforeinput', this.inputHandler) | |
this.element.removeEventListener('paste', this.pasteHandler) | |
} | |
} | |
inputHandler = event => { | |
if ( | |
String(this.element.value).length >= this.digitsValue && | |
event.inputType === 'insertText' | |
) | |
event.preventDefault() | |
} | |
pasteHandler = event => { | |
if ( | |
String(event.clipboardData.getData('text')).length >= this.digitsValue | |
) { | |
event.preventDefault() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment