Ad
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;
}
})
Ad
Answer
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" />
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad