Vue

Vuejs directive for prevent user from writing characters in text box

by antixrist

HTML

<div id="app">
  <h2>Only Numeric Directive Demo:</h2>
  <input v-numeric-only v-model="age"/>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}

JavaScript

// https://vuejs.org/v2/guide/custom-directive.html
// https://alligator.io/vuejs/component-lifecycle/

Vue.directive('numeric-only', {
		bind(el) {
			el.addEventListener('keydown', (e) => {
    	console.log('e.keyCode', e.keyCode);
				if ([46, 8, 9, 27, 13].indexOf(e.keyCode) !== -1 ||
					// Allow: Ctrl+A
					(e.keyCode === 65 && e.ctrlKey === true) ||
					// Allow: Ctrl+C
					(e.keyCode === 67 && e.ctrlKey === true) ||
					// Allow: Ctrl+X
					(e.keyCode === 88 && e.ctrlKey === true) ||
					// Allow: home, end, left, right
					(e.keyCode >= 35 && e.keyCode <= 39)) {
					// let it happen, don't do anything
					return
				}
				// Ensure that it is a number and stop the keypress
				if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
					e.preventDefault()
				}
			})
		}
	});
  
new Vue({
  el: "#app",
  data: {
			age: ''
  },
  methods: {

  }
});