preventing non-numeric values in numeric fields

This commit is contained in:
sairaj mote 2022-07-23 03:25:17 +05:30
parent 3146ec4c75
commit 580d2a64da

View File

@ -471,6 +471,7 @@ customElements.define('sm-input',
this.focusOut = this.focusOut.bind(this); this.focusOut = this.focusOut.bind(this);
this.fireEvent = this.fireEvent.bind(this); this.fireEvent = this.fireEvent.bind(this);
this.checkInput = this.checkInput.bind(this); this.checkInput = this.checkInput.bind(this);
this.handleKeydown = this.handleKeydown.bind(this);
this.vibrate = this.vibrate.bind(this); this.vibrate = this.vibrate.bind(this);
} }
@ -607,6 +608,15 @@ customElements.define('sm-input',
this.feedbackText.textContent = ''; 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() { vibrate() {
this.outerContainer.animate([ this.outerContainer.animate([
{ transform: 'translateX(-1rem)' }, { transform: 'translateX(-1rem)' },
@ -648,6 +658,10 @@ customElements.define('sm-input',
else if (name === 'type') { else if (name === 'type') {
if (this.hasAttribute('type') && this.getAttribute('type') === 'number') { if (this.hasAttribute('type') && this.getAttribute('type') === 'number') {
this.input.setAttribute('inputmode', 'decimal'); this.input.setAttribute('inputmode', 'decimal');
this.input.addEventListener('keydown', this.handleKeydown);
} else {
this.input.removeEventListener('keydown', this.handleKeydown);
} }
} }
else if (name === 'helper-text') { else if (name === 'helper-text') {
@ -685,6 +699,7 @@ customElements.define('sm-input',
disconnectedCallback() { disconnectedCallback() {
this.input.removeEventListener('input', this.checkInput); this.input.removeEventListener('input', this.checkInput);
this.clearBtn.removeEventListener('click', this.clear); this.clearBtn.removeEventListener('click', this.clear);
this.input.removeEventListener('keydown', this.handleKeydown);
} }
}) })
const smNotifications = document.createElement('template') const smNotifications = document.createElement('template')