Check for entering numbers only - javascript

I have a problem
I make a check when you enter upper or lower case letters in the text input to warn that letters cannot be entered but only numbers.
how to make i only enter numbers in the input?
<input type="text" id="texter">
<button onclick="checker()">
START
</button>
checker = () =>{
var texter = document.getElementById('texter').value;
if(texter.search(/[a-z]/)){
alert("letters");
return false;
}
else if(texter.search(/[A-Z]/)){
alert("letters big");
return false;
}
else{
return true;
}
}

For the best user experience, using type="number" on your input is the best bet.
<input type="number" />
If you need it to be a "text" type, one thing you can do is strip any non-numeric character from the string and set the value of the textbox to this string:
const textbox = document.querySelector('#texter');
textbox.onkeyup = event => {
const stripped = event.target.value.replace(/\D/g,'');
textbox.value = stripped;
}
<input id="texter" />

sorry but why don't just use number type of the input
<input type='number'id='texter' />
here you don't need to check for number this input just accept numbers

Related

How to properly control data input?

There is a task to supervise input in . It is necessary to give the ability to enter only strings of numbers ([0-9]) into the entity input. At the same time, if something else is entered, then do not overwrite value and do not display incorrect input in the input. I can't find a solution for my case. Validity check ( target.validity.valid ) didn't work either because I have control over the minimum and maximum lengths. At the same time, I have a universal function for several inputs, but only the entity needs to be checked. Please tell me how to correctly implement the check for input [0-9] and so that nothing else can be entered.
The examples that are on the resource are not suitable because they do not take into account the control of the minimum-maximum length
Below is a shortened code example
const [inputState, setInputState] = useState({title : "", entity: ""})
const handleChangeInputValue = (event) => {
const { target } = event;
const { name, value } = target;
// Need to check for numbers
setInputState({ ...inputState, [name]: value });
};
<input
required
minLength={5}
type="text"
placeholder="Enter name"
name="title"
value={inputState.title}
onChange={handleChangeInputValue}
/>
<input
required
minLength={13}
maxLength={15}
type="text"
placeholder="Enter entity"
name="entity"
value={inputState.entity}
onChange={handleChangeInputValue}
/>
you can use HTML 5
<input type="number" name="someid" />
This will work only in HTML5 complaint browser. Make sure your html document's doctype is:
<!DOCTYPE html>
if(name==='entity' && !value.match(/^\d+$/)) {
return
}

replace empty input with 0 and accept only numbers in input type text

I'm a JS learner. I want to display input values in each line (and it's done) but I want to prevent displaying empty values as empty space and replace them with "0". Also I want to force only numbers in the input. Can anyone help me?
<input type="text" id="user-input" onfocus = "this.value =''">
<button id="submit" onclick="addTo()">Submit</button>
<p class="demo"></p>
const myArr = [];
function addTo() {
myArr.push(document.getElementById("user-input").value);
if(myArr.value = "") {
myArr.value = 0;
}
document.querySelector(".demo").innerHTML = myArr.join("<br />")
}
Like you wrote you on the comments, you should change the input to type="number.
Then you must check if the input value in empty before adding it to the array.
Take a look at the example i create for you. There are other ways to do this, but i wanted to stay true to your original idea. i hope it helps you...
let myArr = [];
function addTo() {
const enteredValue = document.getElementById("user-input").value;
const readyValue = enteredValue === '' ? 0 : enteredValue;
myArr.push(readyValue);
document.querySelector(".demo").innerHTML = myArr.join("<br />")
}
<input type="number" id="user-input" onfocus="this.value =''">
<button id="submit" onclick="addTo()">Submit</button>
<p class="demo"></p>
No need for any javascript you can solve both by
<input type="number" placeholder="0">
Granted the placeholder will only show "0" on screen but will return blank as value

Input type number maxlength 5

I want to limit the input type number to maximum 5 numbers, I am using below code, which is working well, only issue is that for backspace I have to use event.keycode which I dont want to use. Is there any alternative apart from usking keycode of backspace.
var input = document.getElementById('input');
input.addEventListener('keypress',showData,false)
function showData(event)
{
if(event.target.value.length<=5)
{
return true;
}
else
{
event.preventDefault();
}
}
If you want it so if the user tries to type more than 5 numbers it only keeps the 5 numbers:
input.oninput = function() {
if (this.value.length > 5) {
this.value = this.value.slice(0,5);
}
}
Why don't you just use:
<input type="number" max="99999">
This will still not stop a user from manually entering a value larger than 99999, but the input element will be invalid.
<input type="number" max="99999" />
How can I limit possible inputs in a HTML5 "number" element?
<form>
<input required type="text" name="inputname" pattern="[0-9]{5,}">
<input type="submit" value="submit">
</form>

JavaScript string is not a function

When working on a page whenever I call on my second function, validateNumber(), I get a "typeError: String is not a function" message can anyone explain to me why this message is occuring? My code is as follows:
< script type = "text/javascript" >
/* <![CDATA[ */
function validateLetter(dataEntry) {
try {
var textInput = dataEntry.value;
var replacedInput = textInput.replace(/[^A-Za-z]/g);
if (textInput != replacedInput)
throw "You can only enter letters into this field.";
dataEntry.value = replacedInput;
} catch (textInputError) {
window.alert(textInputError)
return false;
}
return true;
}
function validateNumber(dataEntry) {
try {
var textInput = dataEntry.value;
var replacedInput = textInput(/[^0-9]/g);
if (textInput != replacedInput)
throw "You can only enter numbers into this field.";
} catch (numberInputError) {
window.alert(numberInputError)
return false;
}
return true;
}
function validateInput(dataEntry) {
if (navigator.appName == "Microsoft INternet Explorer")
var enteredKey = dataEntry.keyCode;
else if (navigator.appName == "Netscape")
var eneteredKey = dataEntry.charCode;
}
/* ]] */
< /script>
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded" name="dataEntry">
<p>Enter your mother's maiden name:
<input type="text" id="letter1" name="letter1" onkeypress="validateLetter(this)">
</p>
<p>Enter the city you were born in:
<input type="text" id="letter2" name="letter2" onkeypress="validateLetter(this)">
</p>
<p>Enter the street you grew up on:
<input type="text" id="letter3" name="letter3" onkeypress="validateLetter(this)">
</p>
<p>Enter your phone number:
<input type="text" id="number1" name="number1" onkeypress="validateNumber(this)">
</p>
<p>Enter the year you were born:
<input type="text" id="number2" name="number2" onkeypress="validateNumber(this)">
</p>
<p>Enter the number of siblings you have:
<input type="text" id="number3" name="number3" onkeypress="validateNumber(this)">
</p>
<p>
<button type="reset" value="Reset Form">Reset Form</button>
</p>
</form>
I am almost certain this is the problem:
var textInput = dataEntry.value;
var replacedInput = textInput(/[^0-9]/g);
if textInput is a string you cannot pass parameters to it as if it were a function, instead:
var replacedInput = textInput.replace(/[^0-9]/g, ""); // dependening in what you are trying to achieve of course
var replacedInput = textInput(/[^0-9]/g);
That's not how you do search and replace in Javascript.
It's not quite clear what you intended here, but if you wanted to remove non-digits from the string, you'd do that using String.replace():
var replacedInput = textInput.replace(/[^0-9]/g, "");
That being said, an easier way of accomplishing this check would be to skip the replacement entirely and just use String.match() instead:
var textInput = dataEntry.value;
if (textInput.match(/[^0-9]/))
throw "You can only enter letters into this field.";
dataEntry.value = textInput;
You might consider isolating functionality so that functions like validateLetter simply validate that the string they are passed contains only letters, then have the caller function work out what to do if the return value is true or not.
In that case, you end up with very much simpler functions:
function validateLetters(s) {
return /^[a-z]+$/i.test(s);
}
function validateNumbers(s) {
return /^\d+$/.test(s);
}
To validate an input, you can add a class to say what type of validation it should have, e.g.
<input name="letter3" class="letter" onkeypress="validateLetter(this)">
Then the validateInput function can determine which validation function to call based on the class:
function validateInput(element) {
var value = element.value;
// If has class letter, validate is only letters
if (/(\s|^)letter(\s|$)/i.test(element.className)) {
// validate only if there is a value other than empty string
if (!validateLetters(value) && value != '') {
alert('Please enter only letters');
}
}
// If has class number, validate is only numbers
if (/(\s|^)number(\s|$)/i.test(element.className)) {
// validate only if there is a value other than empty string
if (!validateNumbers(element.value) && value != '') {
alert('Please enter only numbers');
}
}
}
Note that keypress is not a good event to use for validation as data can be entered without pressing any keys (e.g. paste from the context menu or drag and drop). Also, the listener doesn't see the value resulting from the keypress, it sees the previous value.
You really only need to perform validation when the form is submitted. Until then, why do you care what the values are? Allow the user to make mistakes and fix them themselves without being pestered by alerts (onscreen hints are really useful). Spend some time using your forms to enhance their usability (I realise this is probably not a production form, but names can have characters other than the letters a to z, e.g. von Braun and O'Reilly).
Lastly, form controls rarely need an ID, the name is usually sufficient to identify them if required (and they must have a name to be successful, so most have a name already). A bit of play HTML from the OP:
<form>
<p>Enter your mother's maiden name:
<input name="letter1" class="letter" onkeypress="validateInput(this)">
</p>
<p>Enter the number of siblings you have:
<input name="number3" class="number" onkeypress="validateInput(this)">
</p>
<p>
<input type="reset">
</p>
</form>

Only allow HTML field to start with certain words

Is there a quick javascript library or code that would only allow a user to start a form input with a preset selection of words?
For example it would allow a user to start a the word "Are" or "What" but not "Why".
You can use the following Regex. (This is really primitive and should be improved according to your case.)
^(Why|Are).*$
HTML5 input pattern example:
<form>
<input type="text" pattern="^(Why|Are).*$">
<input type="submit">
</form>
Test here.
You can add change or input event listener to it and validate the content. To avoid false negatives with initial few letters you can start checking after the input string contains a space. You don't need a library to do that. Plain old JS will do the job.
var input = document.getElementById("myinput");
input.addEventListener('input', validate);
function validate(e) {
var validStart = ['why', 'when'];
var tmpVal;
if (this.value.indexOf(' ') !== -1) {
tmpVal = this.value.toLowerCase().trim();
if (validStart.indexOf(tmpVal) === -1) {
input.classList.add('notvalid');
} else {
input.classList.remove('notvalid');
}
} else {
input.classList.remove('notvalid');
}
}
JSFiddle: http://jsfiddle.net/ofx2yhzm/1/
Very similar to Strah's answer, but here it is anyway:
function checkValue(el) {
// Trim only leading whitespace so responds when first space entered
// and break into words
var words = el.value.replace(/^\s+/,'').split(/\s+/);
// List of allowed words
var allowed = ['are','what'];
// Element to write message based on source element
var msg = document.getElementById(el.id + 'Msg');
// Clear error message by default
msg.innerHTML = '';
// Only do something if at least one word has been entered
// Could also check if first word has more letters than
// longest allowed word
if (words.length > 1) {
// Check if first word is allowed
if ( allowed.indexOf(words[0].toLowerCase()) == -1) {
msg.innerHTML = 'Input must start with one of ' + allowed.join(', ');
}
}
}
Some markup:
<input id="foo" oninput="checkValue(this);">
<span id="fooMsg"></span>
This allows the user to at least enter a word before being given an error. They should also be given some onscreen hints to let them know which words to use, rather than having to get it wrong first (which is bound to happen a lot).
Html:
<form name="myform" method="post" action="#" onsubmit="return validate()">
<input type="text" name="val" />
<input type="submit" value="Submit" />
</form>
Javascript:
window.validate = function(){
data = document.forms['myform']['val'].value;
var starts = ['hi','he'];
for (var i = 0; i <= starts.length; i++)
if (data.indexOf(starts[i]) === 0) return true;
return false;
}
And of course you could also use Regex tho I guess that's a little more inefficient.
Something like this?: http://jsfiddle.net/4jasrbob/

Categories