Lieutenant Dan
Lieutenant Dan

Reputation: 8284

no ability to enter numbers or special chars in input

The below works for the most part; however numbers can still be entered via two ways: 'copy paste' and also from browser cache/suggestions, i.e. if your browser is giving you suggestions from your history to fill the input. Numbers can still be achieved in those two ways.

Anyway to eliminate the ability for numbers being entered in the field completely?

<input type="text" data-value-field="value" name="styleName" onkeypress="return /[a-z]/i.test(event.key)" />

Upvotes: 0

Views: 255

Answers (2)

Daemon Beast
Daemon Beast

Reputation: 2909

onpaste="return false" is used to cancel the paste event.

autocomplete="off" is used to prevent auto-completion.

setInterval(() => { ... }, 100); is used to regularly check the input and remove any numbers or special characters. This prevents the user from being able to use input.value = " ... " in the Developer console to set the input's value to something invalid, as the input will automatically be corrected.

const input = document.getElementById('cleanse');

setInterval(() => {
  input.value = input.value.replace(/[^a-zA-Z ]/g, "");
}, 100);
<input type="text" data-value-field="value" name="styleName" onkeypress="return /[a-z]/i.test(event.key)" onpaste="return false" autocomplete="off" id="cleanse" />

Upvotes: 0

Oleg Om
Oleg Om

Reputation: 439

Check this

abc.oninput = function() {
  const val = this
  if (/[0-9~`!@#$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?£.]+/.test(this.value)) {
const i = this.value.match(/[0-9~`!@#$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?£.]+/g)
if (i !== null) {
  i.map(function(el) {
    val.value = val.value.replace(el, '')
  })
}
  }
}
<input type="text" data-value-field="value" name="styleName" id="abc" />

Upvotes: 1

Related Questions