Nightcrawler
Nightcrawler

Reputation: 1051

allow only numbers in input text box

I want to create simple validation form, which allows only numbers, for example, if i write into input field 223w i want to console.log('error, write only number'), I can not figure out what happens here, i am new in js…

HTML code:

<div class="inputs mt-4" id="with_cash">
    <input id="inpt" type="text" placeholder="enter only number" />
</div>

JavaScript Code:

const test = document.getElementById('inpt')

var extest = test.value

var regex = /^[a-zA-Z]+$/;

var regex2 = /^[0-9]+$/;

//thats not works correctly
withCash.addEventListener('input', function () {

    if (!extest.match(regex)) {
        console.log('error write only number')

    } else if (!extest.match(regex2)) {
        console.log('must input number')
        return false;
    }

})

Upvotes: 1

Views: 2801

Answers (1)

vadimk7
vadimk7

Reputation: 8295

You need:

  • read about regular expressions
  • create a regexp that accepts only numbers /^\d+$/
  • in event handler test input value by the regexp regexp.test(value)

const input = document.getElementById('input')
const onlyNumbersRegExp = /^\d+$/;

input.addEventListener('input', function() {
  if (onlyNumbersRegExp.test(input.value)) {
    console.log('only numbers');
  } else {
    console.log('not only numbers');
  }
})
<input id="input" type="text" placeholder="enter only number" />

Upvotes: 1

Related Questions