How to disAllow minus (-) in text box - javascript

Here I have a function which only allows numeric and percentage. But it is allowing minus(-), I want to restrict that minus in that script. How can I restrict.Here is my script.Or please suggest me a dirctive for this.
function validateQty(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode != 45 && charCode != 8 && charCode != 37 && (charCode != 46) && (charCode < 48 || charCode > 57))
return false;
if (charCode == 46) {
if ((el.value) && (el.value.indexOf('.') >= 0))
return false;
else
return true;
}
return true;
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = evt.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
};

You can allow what you want to be as input. Do something like this.
function restrictInput(el) {
el.addEventListener('input', function(e) {
if (!e.target.value.match(/^\d+$|%$/)) {
e.target.value = e.target.value.slice(0, -1)
}
console.log(e.target.value);
})
}
restrictInput(document.getElementById("input1"));
restrictInput(document.getElementById("input2"));
<input id="input1">
<input id="input2">
updated: As asked by OP. A generic function to handle inputs.
NOTE: You can add more restrictions as you want inside this function

You could use input=number
<input type="number" min="0" />
Using javascript you could do:
// Select your input element.
var numInput = document.querySelector('input');
// Listen for input event on numInput.
numInput.addEventListener('input', function () {
// Let's match only digits.
var num = this.value.match(/^\d+$/);
if (num === null) {
// If we have no match, value will be empty.
this.value = "";
}
}, false)
If the data from the input field will be sent to the server, make sure to add this validation on the server too.

I think you can simplify your script by just testing it against a regular expression.
So your function would essentially change to something like this
function validateQty(el, evt)
{
var regex = new RegExp(/^\d+$|%$/);
return regex.test(el.value);
};
JSFiddle

Related

Add custom country name with different international dial code

I am using https://github.com/jackocnr/intl-tel-input to get flag and international county code.
var phonePrefix = $("#phonePrefix");
phonePrefix.intlTelInput({
preferredCountries: preferredCountries,
onlyCountries: onlyCountries,
});
phonePrefix.on('keydown', function (e) {
//dont allow to input other characters apart from numbers and + sign
if (!isAllowedChar(e)) return false;
//dont allow to remove + sign that appears as first character
if (($(this).get(0).selectionStart == 0 && (e.keyCode < 35 || e.keyCode > 40))
|| ($(this).get(0).selectionStart == 1 && e.keyCode == 8)) {
return false;
}
})
/**
* Allows only to input numbers or the plus sign
*/
function isAllowedChar(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
//allow plus sign
if (charCode === 43) return true;
//allow nav buttons
if (charCode >= 35 && charCode <= 40) return true;
//allow digits
if (charCode >= 48 && charCode <= 57) return true;
//allow backspace
if (charCode === 8) return true;
//allow delete
if (charCode === 46) return true;
return false;
}
And I have flag with international country code. Now I need to add some more international code for some specific country.
If I try add array in var allCountries like
[ "Mexico (México)", "mx", "521" ]
in intlTelInput.js and its works. But I don't want to edit plugin. Is it possible to add without touching plugin?
Thank You

Javascript currency regular expression replace

For my business web application I want a user to only be able to enter valid currency values in a textbox.
Currently I use
$input.val($input.val().replace(/[^.\d]/g, ''));
But this doesn't take in consideration order or multiple decimal seperators.
So the user either has to enter a whole integer or a valid decimal value e.g.:
49
49.50
Bonus points if this is allowed too:
.50 (for 0.50)
So I don't want to validate, I want to restrict typing into the textbox. Is this possible with a single regexp replace?
We can do this in two steps. Restrict the user to type only the number characters and . character.
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode < 31 && (charCode > 48 || charCode < 57))
return true;
return false;
And the next one is for allowing the .:
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode == 46 && (charCode > 31 && (charCode < 48 || charCode > 57)))
return true;
return false;
The next step will be not allowing double periods.
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode == 46 && (charCode > 31 && (charCode < 48 || charCode > 57)))
if (charCode == 46 && value.indexOf(".") !== false)
return true;
return false;
Hope you can have this as a starting point.
Snippet
Open Deal: Break it if you can.
function check(inp) {
var charCode = (event.which) ? event.which : event.keyCode;
console.log(charCode);
if (charCode == 8)
return true;
if ((charCode > 46 && charCode < 58) || (charCode > 95 && charCode < 106) || charCode == 110 || charCode == 190)
if (charCode == 110 || charCode == 190)
if (inp.value.indexOf(".") == -1)
return true;
else
return false;
else
return true;
return false;
}
<input type="text" onkeydown="return check(this);" />
It's more user friendly to advise of errors and let users fix them themselves. You might consider using the keyup event, but showing an error too early (before the user has had a chance to enter a valid value) can be annoying too. e.g.
function validate(el) {
var type = el.className;
var errEl = document.getElementById(el.name + 'Err');
if (type == 'typeCurrency') {
var currencyRe = /^-?(\d+(\.\d{1,2})?|\.\d{1,2})$/;
errEl.style.visibility = currencyRe.test(el.value)? 'hidden' : 'visible';
}
}
.errorMessage {
color: red;
background-color: white;
visibility: hidden;
}
Cost <input onblur="validate(this)" name="foo" class="typeCurrency" placeholder="0.00"><br>
<span id="fooErr" class="errorMessage">Please enter a valid cost, e.g. 2.45</span>

Textbox only allow floating point number

Here is the code in html to allow only one decimal point in a textbox:
<html>
<head>
<script type="text/javascript" language="javascript">
function isNumberKey(evt) {
var charCode = (evt.charCode) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
else {
var input = document.getElementById("txtChar").value;
var len = document.getElementById("txtChar").value.length;
var index = document.getElementById("txtChar").value.indexOf('.');
if (index > 0 && charCode == 46) {
return false;
}
if (index >0 || index==0) {
var CharAfterdot = (len + 1) - index;
if (CharAfterdot > 2) {
return false;
}
}
if (charCode == 46 && input.split('.').length >1) {
return false;
}
}
return true;
}
</script>
</head>
<body>
<input type="text" id="txtChar" onkeypress="return isNumberKey(event)" name="txtChar" class="CsstxtChar" maxlength="4"/>
</body>
</html>
I want to done this in asp.net using c#.This code is not properly working in asp.net.
use this it would be helpful....
$('.urInputField').keyup(function(e){
var val = $(this).val();
var regexTest = /^\d{0,8}(\.\d{1,2})?$/;
var ok = regexTest.test(val);
if(ok) {
$(this).css('background-color', 'green');
} else {
$(this).css('background-color', 'red');
}
});
the id of controls may differ from what you enter in asp.net source for example when you use parent-child controls or use master pages... , So, you can not use document.getElementById simply.
as i see your code is not just to block non-digit keys as other ones suggest duplicate solutions, but it also block backspace or arrow keys and put a limit on number of digits after decimal point such that only one digit is allowed after dot. i don't change these custom algorithm you used in your code.
this code get the source element which causes the keypress from event parameters:
<script type="text/javascript" language="javascript">
function isNumberKey(event) {
var e = event || window.event;
var src = e.srcElement || e.target;
var charCode = e.which || e.keyCode || e.charCode;
//document.getElementById("label").value = src.id; //just for test/debug
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
else
{
var input = src.value;
var len = input.length;
var index = input.indexOf('.');
if (index > 0 && charCode == 46) return false;
if (index > 0 || index == 0) {
var CharAfterdot = (len + 1) - index;
if (CharAfterdot > 2) return false;
}
if (charCode == 46 && input.split('.').length > 1) {
return false;
}
}
return true;
}
</script>
Use this Source will work good for float numbers
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
thanks Vamsi

Allowing only numbers and one decimal

Guys and gals i have this piece of JavaScript code that only allows for numbers and one decimal period. The problem i'm having is that when i tab over to my textbox controls it highlights the value but i have press backspace to erase then enter a number. That is an extra keystroke that i want to prevent.
Props to the guy who created it found (http://www.coderanch.com/t/114528/HTML-CSS-JavaScript/decimal-point-restriction) and here is the code. I put this on keyUp event.
<script>
// Retrieve last key pressed. Works in IE and Netscape.
// Returns the numeric key code for the key pressed.
function getKey(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
function restrictChars(e, obj)
{
var CHAR_AFTER_DP = 2; // number of decimal places
var validList = "0123456789."; // allowed characters in field
var key, keyChar;
key = getKey(e);
if (key == null) return true;
// control keys
// null, backspace, tab, carriage return, escape
if ( key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
// get character
keyChar = String.fromCharCode(key);
// check valid characters
if (validList.indexOf(keyChar) != -1)
{
// check for existing decimal point
var dp = 0;
if( (dp = obj.value.indexOf( ".")) > -1)
{
if( keyChar == ".")
return false; // only one allowed
else
{
// room for more after decimal point?
if( obj.value.length - dp <= CHAR_AFTER_DP)
return true;
}
}
else return true;
}
// not a valid character
return false;
}
</script>
<input type="text" class="decimal" value="" />
And in Js use this
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9\.]/g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
Check this fiddle: http://jsfiddle.net/2YW8g/
THis worked for me, i have taken this answer from "Nickalchemist" and take none of its credit.
If you can't use an already stable and well-know library, you can try something like this:
document.write('<input id="inputField" onkeyup="run(this)" />');
function run(field) {
setTimeout(function() {
var regex = /\d*\.?\d?/g;
field.value = regex.exec(field.value);
}, 0);
}
I know it doesn't prevent the wrong char to appear, but it works.
PS: that setTimeout(..., 0) is a trick to execute the function after the value of the field has already been modified.
Here is a sample solution that will accept a number with one(1) decimal point only. e.g 1.12, 11.5
Enter a number with one(1) decimal point only<br />
<input type="text" id="decimalPt"> <br />
$('.decimalPt').keypress(function(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 8 || charCode == 37) {
return true;
} else if (charCode == 46 && $(this).val().indexOf('.') != -1) {
return false;
} else if (charCode > 31 && charCode != 46 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
});
Take a look at this: https://jsfiddle.net/sudogem/h43r6g7v/12/
I think it would be best to use something that already exists... like Masked Input Plugin with jQuery
Try this,
$('input').on('keydown', function (event) {
return isNumber(event, this);
});
function isNumber(evt, element) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode != 190 || $(element).val().indexOf('.') != -1) // “.” CHECK DOT, AND ONLY ONE.
&& (charCode != 110 || $(element).val().indexOf('.') != -1) // “.” CHECK DOT, AND ONLY ONE.
&& ((charCode < 48 && charCode != 8)
|| (charCode > 57 && charCode < 96)
|| charCode > 105))
return false;
return true;
}
Be sure to test on any browser. The accepted answer doesn't work on Firefox.
Try HTML5 type number:
<input type="number" placeholder="1.0" step="0.1">
You could define min="0" max="10"
Reference:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#Controlling_input_size
Note: type="number" is not supported in Internet Explorer 9 and earlier versions.
I solve my problem with like this.
const sanitize = (value = '') => value.replace(/(-(?!\d))|[^0-9|-]/g, '') || ''
export const toNumeric = value => {
let digits = sanitize(value)
// parseInt with 0 fix/avoid NaN
digits = parseInt(0 + digits)
let newValue = digits.toString().padStart(4, 0)
return newValue
}

how to define event below

I have a function below where it doesn't allow the user to type in letters in a textbox but it keeps saying event is undefined. Where and how am I suppose to define event?
Below is the function:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
Below is the html where this could be used:
onkeypress="return isNumberKey(event)"
change
var charCode = (evt.which) ? evt.which : event.keyCode
to
var charCode = (evt.which) ? evt.which : evt.keyCode
or if you are using jQuery (you tagged it but aren't using it) you could do
$('#textareaid').keypress(function(e) {
if (e.which > 31 && (e.which < 48 || e.which > 57)) {
e.preventDefault();
}
});
where your html is
<textarea id="textareaid"></textarea>
See event.preventDefault()
Note on how to get key pressed using jQuery
To determine which character was entered, examine the event object
that is passed to the handler function. While browsers use differing
properties to store this information, jQuery normalizes the .which
property so you can reliably use it to retrieve the character code.
Taken from the .keypress() docs
here is the code which should work:
function checkerFunction(e){
var charCode=e.which || e.keyCode;
if(charCode<=31 || charCode>=48 && charCode<=57)return true;
return false;
}
and the event binding should be
onkeypress="return checkerFunction(window.event)"
For the record I think that most of the answers above don't take into consideration the ARROW keys.
This should be how it works incase you are googling this.
function isNumberKey(event)
{
var charCode = event.charCode;
if ((charCode < 48 || charCode > 57) && charCode != 0){
return false;
}
return true;
}

Categories