From 580d2a64dae4b58a7e3b367b98cc38e9d35924a5 Mon Sep 17 00:00:00 2001 From: sairaj mote Date: Sat, 23 Jul 2022 03:25:17 +0530 Subject: [PATCH] preventing non-numeric values in numeric fields --- components.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/components.js b/components.js index 9d96ecb..00f7e0e 100644 --- a/components.js +++ b/components.js @@ -471,6 +471,7 @@ customElements.define('sm-input', this.focusOut = this.focusOut.bind(this); this.fireEvent = this.fireEvent.bind(this); this.checkInput = this.checkInput.bind(this); + this.handleKeydown = this.handleKeydown.bind(this); this.vibrate = this.vibrate.bind(this); } @@ -607,6 +608,15 @@ customElements.define('sm-input', this.feedbackText.textContent = ''; } } + handleKeydown(e) { + if (e.key.length === 1) { + if (!['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.'].includes(e.key)) { + e.preventDefault(); + } else if (e.key === '.' && e.target.value.includes('.')) { + e.preventDefault(); + } + } + } vibrate() { this.outerContainer.animate([ { transform: 'translateX(-1rem)' }, @@ -648,6 +658,10 @@ customElements.define('sm-input', else if (name === 'type') { if (this.hasAttribute('type') && this.getAttribute('type') === 'number') { this.input.setAttribute('inputmode', 'decimal'); + this.input.addEventListener('keydown', this.handleKeydown); + } else { + this.input.removeEventListener('keydown', this.handleKeydown); + } } else if (name === 'helper-text') { @@ -685,6 +699,7 @@ customElements.define('sm-input', disconnectedCallback() { this.input.removeEventListener('input', this.checkInput); this.clearBtn.removeEventListener('click', this.clear); + this.input.removeEventListener('keydown', this.handleKeydown); } }) const smNotifications = document.createElement('template')