Textbox that allows values -9999 to 9999 - javascript

Hello this is what I have right now to allow only numbers and a max of 4 digits. How would I make it so that I can allow a - before the number which would bypass the max 4 digit limit? Currently if I use a - only 3 numbers can be entered after, while I need to make it allow 4 numbers.
// Only Numbers can be Entered
function fNumOnly(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode >= 48 && charCode <= 57) || charCode == 45) {
return true;
}
return false;
}
<input id="txtFahrenheit" type="text" onkeypress="return fNumOnly(event);" maxlength="4" />

Why not use <input type="number"> with min and max values? For example:
input:valid {
border-color: green;
}
input:invalid {
border-color: red;
}
<div>Enter a number between -9999 and 9999 (green for valid entry, red for invalid entry)</div>
<input type="number" name="num" min="-9999" max="9999" required>

You can check length of value of input using regex.
function fNumOnly(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (
((charCode >= 48 && charCode <= 57) || charCode == 45) &&
evt.target.value.match(/^-?\d{0,3}$/g)
) {
return true;
}
return false;
}
<input id="txtFahrenheit" type="text" onkeypress="return fNumOnly(event);" />
Also you can use type=number and min&max attribute for input instead of checking charCode in function
function fNumOnly(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (evt.target.value.match(/^-?\d{0,3}$/g))
return true;
return false;
}
<input id="txtFahrenheit" type="number" onkeypress="return fNumOnly(event);" min="-9999" max="9999"/>

You can add an event listener to your desired button instead, and then upon firing of that event, run the specified function.
var input = document.getElementById("txtFahrenheit");
input.addEventListener("input", function() {
if (input.value < -9999) {
input.value = -9999;
} else if (input.value > 9999) {
input.value = 9999;
}
});
<input id="txtFahrenheit" type="number" min="-9999" max="9999">
By setting the input type to number, we don't have to have code that checks for the input char. By adding max and min to it, we don't allow a user to use the up and down arrows to reach an invalid range.
The attached code however, double ensures this. If they input anything, it will immediately be reverted to the max and min values.
Without it, someone could manually type in 100000 and it would work.

You could do this:
<input id="txtFahrenheit" type="text" maxlength="4">
Then have the script:
const input = document.getElementById("txtFahrenheit");
input.addEventListener("input", () => {
if(input.value.indexOf("-") != -1) input.maxLength = 5;
else input.maxLength = 4;
});
This will let you type four characters in the input field, unless there is a minus among them, in which case, the max will be five characters.

Try Below:
<input id="txtFahrenheit" type="number" oninput="checkLength(this);" />
<script>
function checkLength(inp)
{
if (inp.value > 0)
{
if (inp.value.length > 4)
{
inp.value = inp.value.slice(0, 4);
}
}
else
{
if (inp.value.length > 5)
{
inp.value = inp.value.slice(0, 5);
}
}
}
</script>

Related

Only 4 digit numbers in input field in MVC TextBoxFor

I have an MVC5 project and I have an input field that I only want to take an 8 digit number. I tried implementing it like this:
#Html.TextBoxFor(model => model.oldPin, new { maxlength = "8", #class = "form-control disablecopypaste", onkeydown = "return isNumber(event);" })
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode === 16) {
return false;
}
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
My problem is that while this prevents numbers it allows spaces and special characters. How do I prevent this? It works with the keypress event but its depreciated and I'm concerned about browser compatibility. Is there any way to do this with the keydown event? All the answers I've seen are all with the keypress event.
function allowNumberOnly (e) {
var ascii = (e.which) ? e.which : e.keyCode
if (ascii> 31 && (ascii< 48 || ascii> 57)) {
return false;
}
else {
var vall = $('#oldPin').val()
if (vall.length > 3) {
return false;
}
else {
return true;
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control " id="oldPin" name="oldPin" onkeypress="return allowNumberOnly(event)" type="text" value="">

How to allow only numbers as input in Javascript , why doesn't my code work?

I want write a function to prevent any input other than numbers 0-9 and the return key so the user can make corrections. I know that this type of question have been asked several times but why doesn't my code work. Does it has to do with the shift key? Why am I getting "event is not defined"?
In the snippet I can prevent letters but special characters, like #, keep being inserted. Why am I getting a reference error?
// I have two functions
function formatarCPF(event, controle) {
//this line check the returned value from the functions defined below
var eNumero = permitirApenasNumeros(event.keyCode);
if (!eNumero)
event.preventDefault();
if (event.keyCode != 8) {
var valor = controle.value;
if (valor.length == 3) {
controle.value = (controle.value + ".");
}
if (valor.length == 7) {
controle.value = (controle.value + ".");
}
if (valor.length == 11) {
controle.value = (controle.value + "-");
}
}
}
if(event.keyCode != 8) {
var valor = controle.value;
if (valor.length == 0) {
controle.value = "(";
}
if(valor.length == 2) {
controle.value = (controle.value + String.fromCharCode(event.which) + ")");
event.preventDefault();
}
if (valor.length == 9) {
controle.value = (controle.value + "-");
}
}
function permitirApenasNumeros(code) {
//checks to see if the user typed a number
var regex = /[0-9]/;
if(regex.test(String.fromCharCode(code)) || code == 8) {
return true;
} else {
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div>
<label for="tbCPF">CPF:</label>
<input onkeydown="formatarCPF(event, this)" maxlength="14" placeholder="___.___.___-__" />
</div>
Try HTML5
<input type="number" />
Or regex
<input type="text" pattern="^[0-9]*$" />
Your code formatting has many issues that make it nearly impossible to read, but it seems to me that the problem is your second if(event.keyCode != 8) { block that is outside the formatarCPF event listener. Since it is outside, the event variable isn't defined.
If you format your code properly this would be super trivial to catch. You can use tools like jsbeautifier to do it for you if you prefer.
To allow only numbers inside an HTML Input Element just set its type to number
<input min='0' type="number">
Why not simply scrap all that JavaScript and use:
<input type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57">
This should work
HTML
<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />
JAVASCRIPT
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}

How to Disable Paste option for alphabets and Special Characters but Enabled for Numbers

I Used this code for restricting to type alphabets and characters.
<script type="text/javascript">
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
</script>
<asp:TextBox ID="txtCode" runat="server" Width="15%" onkeypress="return isNumber(event)"/>
But I am able to Paste the alphabets and characters in it(Which I don't want).
When I used this code, The Paste Option is disabled but,I cant Paste even Numbers
<asp:TextBox ID="txtCode" runat="server" Width="15%" ondrop="return false;"
onpaste="return false;" onkeypress="return isNumber(event)" />
But I want to paste the Numbers :(,How can I do that ?.
First of all you should use type="number" to have a semantic meaning and form validation like HtML5 in mordern browser, and to get the live functionality in all the browser you can try this:
function isNumber(ev) {
if (ev.type === "paste" || ev.type === "drop") {
var textContent = (ev.type === "paste" ? ev.clipboardData : ev.dataTransfer).getData('text');
return !isNaN(textContent) && textContent.indexOf(".") === -1;
} else if (ev.type === "keydown") {
if (ev.ctrlKey || ev.metaKey) {
return true
};
var keysToAllow = [8, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
return keysToAllow.indexOf(ev.keyCode) > -1;
} else {
return true
}
}
<input type="number" placeholder="paste numbers only" name="" onpaste="return isNumber(event)" onkeydown="return isNumber(event)" ondrop="return isNumber(event)">
Remove the second condition if && pasteContent.indexOf(".")===-1 if you want to allow integer as well as floating point numbers. but allowing floating point number will cause a problem if you already have a floating point number, so it will be invalid number with two "."
Below is a solution using a timeout.
<!DOCTYPE html>
<html>
<body>
<input type="text" id="inputText" onpaste="return isNumber(event);" onkeypress="return isNumber(event)" value="" size="40">
<p id="demo"></p>
<script>
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var element = document.getElementById("inputText");
var initialValue = element.value;
if(evt.type == "paste"){
setTimeout(function() {
var value = element.value;
var pastedText = value.replace(initialValue,"");
if(!isNaN(pastedText)){
element.value = value;
}else{
element.value = initialValue;
}
}, 2);
}
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
</script>
</body>
</html>

Javascript validation: Block special characters From input text box when click on submit

How can I restrict entering special characters in the text box (txt_edition) by editing below code for validation? I want only numbers to be entered.
<script>
function validateForm()
{
var x = document.forms["frm_bokAdd"]["txt_edition"].value;
if (x==null || x=="")
{
alert("Edition must be filled out");
return false;
}
</script>
Below is my form
<form name="frm_bokAdd" action ="#" method="post" onsubmit="return validateForm()" >
<table border="0" align="center">
<tr><td> <input type="text" name="txt_edition" ></td></tr>
<tr><td> <input type="submit" name="bookIns_submit" value="Add"></td></tr>
</table>
</form>
can use this
HTML
<input type="text" onkeypress="return isNumber(event)" >
JS(at end of Body )
function isNumber(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
DEMO is Here
How can I restrict entering special characters in the text box (txt_edition)
Don't. Allow users to arrive at a valid value any way they like, you really only care that the value is valid when it's sent to the server, and even then you should validate there too.
by editing below code for validation? I want only numbers to be entered.
Just test when the form is submitted, passing a reference to the form in the call:
<form ... onsubmit="return validateForm(this)" >
and the function:
function validateForm(form) {
var value = form.txt_edition.value;
if (/\D/.test(value) || value == '') {
alert("Edition must be filled out and contain only numbers");
return false;
}
}
use regex.
if (x.match(/^[0-9]*\.[0-9]*$/) !== null) {
//text is only numbers (use /^[0-9]*$/ for integers)
}
Try it
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
body
{
font-size: 9pt;
font-family: Arial;
}
</style>
</head>
<body>
Alphanumeric value:
<input type="text" id="text1" onkeypress="return IsAlphaNumeric(event);" ondrop="return false;"
onpaste="return false;" />
<span id="error" style="color: Red; display: none">* Special Characters not allowed</span>
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
function IsAlphaNumeric(e) {
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
</script>
</body>
</html>
Try to use regular expression -
var edition = document.getElementById('txt_edition').value;
outputVal = edition.replace(/[^0-9a-zA-Z]/g,"");
if (edition != outputVal) {
return false;
}
You can restrict the key press like below,
function restrict_letters(e) {
var keyCode = e . keyCode == 0 ? e . charCode : e . keyCode;
// only 0 to 9
if (keyCode < 48 && keyCode > 57) {
return false;
}
}
you can get more key codes in here.
Also change the html function call like below,
<input type="text" onkeypress="return restrict_letters(event)">
Note: function call need to give for the input field not for the form submit.
To allow user to enter only number and dot. Use this regular expression
function NumAndTwoDecimals(event , obj){
reg = /[^0-9.,]/g;
obj.value = obj.value.replace(reg,"");
}
SEE DEMO HERE
HTML code is
<input id="txtId" type="text" onkeyup="NumAndTwoDecimals(event , this);"></input>
To restrict user to enter only two number after '.' operator use
function NumAndTwoDecimals(e , field) {
var val = field.value;
var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
if (re.test(val)) {
//do something here
} else {
val = re1.exec(val);
if (val) {
field.value = val[0];
} else {
field.value = "";
}
}
}
SEE DEMO HERE

Allow only numbers to be typed in a textbox - default to zero

How can this be modified so that if a user does not enter a number the number 0 will be entered into the text field, thank you in advance:
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
if a user does not enter a number then 0 will be entered into the text field
<input type="text" id="numeric" value="0" onclick="this.value='' " onblur="if(this.value==''){ this.value='0'} " />
regex for numbers only.
$('#numeric').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
DEMO
Use IsNumeric and check if 0 too.
IsNumeric(number goes here)

Categories

Resources