Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to block every number from being entered in text field

I want to completely not allow a user to input any number in a text field, how can I make this work with js? I am trying to replace the numbers with regex but doesn’t seem to work

const selectElement = document.querySelector('.ice-cream');

selectElement.addEventListener('change', (event) => {
  const result = document.querySelector('.result');
  let temp = event.target.value.replace(/[^0-9]/g, '');
  result.textContent = `${temp}`;
});
<input type="text" class="ice-cream">
<p class="result">
</p>

I have also tried this

const selectElement = document.querySelector('.ice-cream');

selectElement.addEventListener('change', (event) => {
  const result = document.querySelector('.result');
  let pattern = new RegExp(/[A-Z]/i);
  if(pattern.test(event.target.value)) {
    result.textContent = `${event.target.value}`;

  } else return;
});

It seems not to allow any number at start but when I enter a text and then number then it allows when it shouldn’t. Can someone give me advice?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should invert your regex pattern to [0-9] without the ^, because that matches anything that tis not a digit.

Also, you might want to consider replacing the input element’s value as well.

const selectElement = document.querySelector('.ice-cream');

selectElement.addEventListener('input', (event) => {
  const result = document.querySelector('.result');
  event.target.value = event.target.value.replace(/[0-9]/g, '');
  result.textContent = `${event.target.value}`;
});
<input type="text" class="ice-cream">
<p class="result">
</p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading