Allowing only numbers and one decimal - javascript

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
}

Related

Limit textbox to 10 digits with and also with allowed decimals in jquery

I've been stuck on a problem and searching for it, but couldn't find one.
I have a text field where I want to allow 10 digits and decimal values, for example my allowed digits would be:
1.11
1234567890
Anything within 10 digit range (have problems in these cases below)
12345678.13
123456789.05
1234567890.12
I can already restrict textbox to 10 digits but the question is how to allow only 2 decimals after 10 digits.
My code is:
function CheckNumber(textBoxValue,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 && textBoxValue.indexOf('.') != -1) {
return false;
} else if (charCode > 31 && charCode != 46 && (charCode < 48 || charCode > 57)) {
return false;
}
console.log(charCode);
if(textBoxValue.length){
newVal = textBoxValue.split('.');
console.log(newVal);
if(newVal[0].length > 9){
if(charCode == 46){
return true;
}
return false;
}
}
return true;
}
Uhhmm, why not use regex for this? Here is a working fiddle:
https://jsfiddle.net/L18d0qut/3/
EDIT:
I changed the code accordingly. Is this fiddle working for you?
I modified the checks to meet your criteria. The key code is now this:
$('#input').on('keyup', function(){
var value = $(this).val();
if(value.match(/^[0-9,.]*$/)) {
if(value.indexOf(".") >= 0 || value.indexOf(",") >= 0){
console.log("YAY, we have a float, so it is valid!");
} else if(value.length <= 10) {
console.log("Valid!");
} else {
console.log("invalid!");
}
} else {
console.log("Only numbers and . or , are allowed!");
}
});
NOTE: This works for floating numbers with . and also with ,. If you do not want this you can simply modify to your needs in the regex and indexOf() methods.
I check the length of the input AND check for the contents by regex. Is this what you're looking for?
Just have a look in the console for the result :-).
I have modified your code & created something like this.
function CheckNumber(textBoxValue,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 && textBoxValue.indexOf('.') != -1) {
return false;
} else if (charCode > 31 && charCode != 46 && (charCode < 48 || charCode > 57)) {
return false;
}
//console.log(charCode);
if(textBoxValue.length){
newVal = textBoxValue.split('.');
/*console.log(newVal[1]);*/
if(typeof(newVal[1])!='undefined'){
if(newVal[1].length !=2){
return true;
}else{
return false;
}
}
if(newVal[0].length > 9){
if(charCode == 46){
return true;
}
if((charCode >= 48 || charCode <=57) && newVal[0].length == 10 && textBoxValue.indexOf('.') != -1 ){
if(newVal[1].length !=2){
return true;
}else{
return false;
}
}
return false;
}
}
return true;
}
You can check
if(newVal[1].length > 2){
// your code
}
Try this..............
function CheckNumber(textBoxValue,evt){
var a = textBoxValue.replace('.', '');
if(a.length <= 10){
console.log("valid");
} else {
console.log("invalid");
}
}
Try this:
function IsValid(input) {
return (/^\d{0,10}(\.\d{0,2})?$/).test(input);
}
This allows 10 digits and 2 (optional) decimals. Input must be string.
This code allow you only two decimal digits and 10 number before decimal point
/^\d {0,12} (.\d{0,2})?$/;
you can set your textbox length by {0,12} where 0 : min length and 12 : max length
function IsValidNumber(Number) {
var expr = /^\d{0,12}(\.\d{0,2})?$/;
return expr.test(Number);
};
function ValidateNumber() {
var Number = document.getElementById("txtNumber").value;
if (!IsValidNumber(Number)) {
alert("Invalid number");
}
else {
alert("Valid number.");
}
}
<input type="text" id="txtNumber" />
<input type="button" id="btnValidate" value="Validate" onclick = "ValidateNumber()" />
Have you considered textbox input pattern using regex?
Something like pattern="\d{10}\.\d{2}$"

How to disAllow minus (-) in text box

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

best way to restrict special characters in text field input [duplicate]

How do I block special characters from being typed into an input field with jquery?
A simple example using a regular expression which you could change to allow/disallow whatever you like.
$('input').on('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
I was looking for an answer that restricted input to only alphanumeric characters, but still allowed for the use of control characters (e.g., backspace, delete, tab) and copy+paste. None of the provided answers that I tried satisfied all of these requirements, so I came up with the following using the input event.
$('input').on('input', function() {
$(this).val($(this).val().replace(/[^a-z0-9]/gi, ''));
});
Edit:
As rinogo pointed out in the comments, the above code snippet forces the cursor to the end of the input when typing in the middle of the input text. I believe the code snippet below solves this problem.
$('input').on('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
Short answer: prevent the 'keypress' event:
$("input").keypress(function(e){
var charCode = !e.charCode ? e.which : e.charCode;
if(/* Test for special character */ )
e.preventDefault();
})
Long answer: Use a plugin like jquery.alphanum
There are several things to consider when picking a solution:
Pasted text
Control characters like backspace or F5 may be prevented by the above code.
é, í, ä etc
Arabic or Chinese...
Cross Browser compatibility
I think this area is complex enough to warrant using a 3rd party plugin. I tried out several of the available plugins but found some problems with each of them so I went ahead and wrote jquery.alphanum. The code looks like this:
$("input").alphanum();
Or for more fine-grained control, add some settings:
$("#username").alphanum({
allow : "€$£",
disallow : "xyz",
allowUpper : false
});
Hope it helps.
Use simple onkeypress event inline.
<input type="text" name="count" onkeypress="return /[0-9a-zA-Z]/i.test(event.key)">
Use HTML5's pattern input attribute!
<input type="text" pattern="^[a-zA-Z0-9]+$" />
Use regex to allow/disallow anything. Also, for a slightly more robust version than the accepted answer, allowing characters that don't have a key value associated with them (backspace, tab, arrow keys, delete, etc.) can be done by first passing through the keypress event and check the key based on keycode instead of value.
$('#input').bind('keydown', function (event) {
switch (event.keyCode) {
case 8: // Backspace
case 9: // Tab
case 13: // Enter
case 37: // Left
case 38: // Up
case 39: // Right
case 40: // Down
break;
default:
var regex = new RegExp("^[a-zA-Z0-9.,/ $#()]+$");
var key = event.key;
if (!regex.test(key)) {
event.preventDefault();
return false;
}
break;
}
});
Your textbox:
<input type="text" id="name">
Your javascript:
$("#name").keypress(function(event) {
var character = String.fromCharCode(event.keyCode);
return isValid(character);
});
function isValid(str) {
return !/[~`!##$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
Take a look at the jQuery alphanumeric plugin. https://github.com/KevinSheedy/jquery.alphanum
//All of these are from their demo page
//only numbers and alpha characters
$('.sample1').alphanumeric();
//only numeric
$('.sample4').numeric();
//only numeric and the .
$('.sample5').numeric({allow:"."});
//all alphanumeric except the . 1 and a
$('.sample6').alphanumeric({ichars:'.1a'});
this is an example that prevent the user from typing the character "a"
$(function() {
$('input:text').keydown(function(e) {
if(e.keyCode==65)
return false;
});
});
key codes refrence here:
http://www.expandinghead.net/keycode.html
I use this code modifying others that I saw. Only grand to the user write if the key pressed or pasted text pass the pattern test (match) (this example is a text input that only allows 8 digits)
$("input").on("keypress paste", function(e){
var c = this.selectionStart, v = $(this).val();
if (e.type == "keypress")
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode)
else
var key = e.originalEvent.clipboardData.getData('Text')
var val = v.substr(0, c) + key + v.substr(c, v.length)
if (!val.match(/\d{0,8}/) || val.match(/\d{0,8}/).toString() != val) {
e.preventDefault()
return false
}
})
$(function(){
$('input').keyup(function(){
var input_val = $(this).val();
var inputRGEX = /^[a-zA-Z0-9]*$/;
var inputResult = inputRGEX.test(input_val);
if(!(inputResult))
{
this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
}
});
});
Write some javascript code on onkeypress event of textbox.
as per requirement allow and restrict character in your textbox
function isNumberKeyWithStar(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 42)
return false;
return true;
}
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
function isNumberKeyForAmount(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
return true;
}
To replace special characters, space and convert to lower case
$(document).ready(function (){
$(document).on("keyup", "#Id", function () {
$("#Id").val($("#Id").val().replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '').toLowerCase());
});
});
Yes you can do by using jQuery as:
<script>
$(document).ready(function()
{
$("#username").blur(function()
{
//remove all the class add the messagebox classes and start fading
$("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
//check the username exists or not from ajax
$.post("user_availability.php",{ user_name:$(this).val() } ,function(data)
{
if(data=='empty') // if username is empty
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Empty user id is not allowed').addClass('messageboxerror').fadeTo(900,1);
});
}
else if(data=='invalid') // if special characters used in username
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Sorry, only letters (a-z), numbers (0-9), and periods (.) are allowed.').addClass('messageboxerror').fadeTo(900,1);
});
}
else if(data=='no') // if username not avaiable
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('User id already exists').addClass('messageboxerror').fadeTo(900,1);
});
}
else
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('User id available to register').addClass('messageboxok').fadeTo(900,1);
});
}
});
});
});
</script>
<input type="text" id="username" name="username"/><span id="msgbox" style="display:none"></span>
and script for your user_availability.php will be:
<?php
include'includes/config.php';
//value got from the get method
$user_name = trim($_POST['user_name']);
if($user_name == ''){
echo "empty";
}elseif(preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-]/', $user_name)){
echo "invalid";
}else{
$select = mysql_query("SELECT user_id FROM staff");
$i=0;
//this varible contains the array of existing users
while($fetch = mysql_fetch_array($select)){
$existing_users[$i] = $fetch['user_id'];
$i++;
}
//checking weather user exists or not in $existing_users array
if (in_array($user_name, $existing_users))
{
//user name is not availble
echo "no";
}
else
{
//user name is available
echo "yes";
}
}
?>
I tried to add for / and \ but not succeeded.
You can also do it by using javascript & code will be:
<!-- Check special characters in username start -->
<script language="javascript" type="text/javascript">
function check(e) {
var keynum
var keychar
var numcheck
// For Internet Explorer
if (window.event) {
keynum = e.keyCode;
}
// For Netscape/Firefox/Opera
else if (e.which) {
keynum = e.which;
}
keychar = String.fromCharCode(keynum);
//List of special characters you want to restrict
if (keychar == "'" || keychar == "`" || keychar =="!" || keychar =="#" || keychar =="#" || keychar =="$" || keychar =="%" || keychar =="^" || keychar =="&" || keychar =="*" || keychar =="(" || keychar ==")" || keychar =="-" || keychar =="_" || keychar =="+" || keychar =="=" || keychar =="/" || keychar =="~" || keychar =="<" || keychar ==">" || keychar =="," || keychar ==";" || keychar ==":" || keychar =="|" || keychar =="?" || keychar =="{" || keychar =="}" || keychar =="[" || keychar =="]" || keychar =="¬" || keychar =="£" || keychar =='"' || keychar =="\\") {
return false;
} else {
return true;
}
}
</script>
<!-- Check special characters in username end -->
<!-- in your form -->
User id : <input type="text" id="txtname" name="txtname" onkeypress="return check(event)"/>
just the numbers:
$('input.time').keydown(function(e) { if(e.keyCode>=48 &&
e.keyCode<=57) {
return true; } else {
return false; } });
or for time including ":"
$('input.time').keydown(function(e) { if(e.keyCode>=48 &&
e.keyCode<=58) {
return true; } else {
return false; } });
also including delete and backspace:
$('input.time').keydown(function(e) { if((e.keyCode>=46 &&
e.keyCode<=58) || e.keyCode==8) { return true; } else {
return false; } });
unfortuneatly not getting it to work on a iMAC
Wanted to comment on Alex's comment to Dale's answer. Not possible (first need how much "rep"? That wont happen very soon.. strange system.)
So as an answer:
Backspace can be added by adding \b to the regex definition like this: [a-zA-Z0-9\b].
Or you simply allow the whole Latin range, including more or less anything "non exotic" characters (also control chars like backspace): ^[\u0000-\u024F\u20AC]+$
Only real unicode char outside latin there is the euro sign (20ac), add whatever you may need else.
To also handle input entered via copy&paste, simply also bind to the "change" event and check the input there too - deleting it or striping it / giving an error message like "not supported characters"..
if (!regex.test($j(this).val())) {
alert('your input contained not supported characters');
$j(this).val('');
return false;
}
Restrict specials characters on keypress. Here's a test page for key codes: http://www.asquare.net/javascript/tests/KeyCode.html
var specialChars = [62,33,36,64,35,37,94,38,42,40,41];
some_element.bind("keypress", function(event) {
// prevent if in array
if($.inArray(event.which,specialChars) != -1) {
event.preventDefault();
}
});
In Angular, I needed a proper currency format in my textfield. My solution:
var angularApp = angular.module('Application', []);
...
// new angular directive
angularApp.directive('onlyNum', function() {
return function( scope, element, attrs) {
var specialChars = [62,33,36,64,35,37,94,38,42,40,41];
// prevent these special characters
element.bind("keypress", function(event) {
if($.inArray(event.which,specialChars) != -1) {
prevent( scope, event, attrs)
}
});
var allowableKeys = [8,9,37,39,46,48,49,50,51,52,53,54,55,56
,57,96,97,98,99,100,101,102,103,104,105,110,190];
element.bind("keydown", function(event) {
if($.inArray(event.which,allowableKeys) == -1) {
prevent( scope, event, attrs)
}
});
};
})
// scope.$apply makes angular aware of your changes
function prevent( scope, event, attrs) {
scope.$apply(function(){
scope.$eval(attrs.onlyNum);
event.preventDefault();
});
event.preventDefault();
}
In the html add the directive
<input only-num type="text" maxlength="10" id="amount" placeholder="$XXXX.XX"
autocomplete="off" ng-model="vm.amount" ng-change="vm.updateRequest()">
and in the corresponding angular controller I only allow there to be only 1 period, convert text to number and add number rounding on 'blur'
...
this.updateRequest = function() {
amount = $scope.amount;
if (amount != undefined) {
document.getElementById('spcf').onkeypress = function (e) {
// only allow one period in currency
if (e.keyCode === 46 && this.value.split('.').length === 2) {
return false;
}
}
// Remove "." When Last Character and round the number on blur
$("#amount").on("blur", function() {
if (this.value.charAt(this.value.length-1) == ".") {
this.value.replace(".","");
$("#amount").val(this.value);
}
var num = parseFloat(this.value);
// check for 'NaN' if its safe continue
if (!isNaN(num)) {
var num = (Math.round(parseFloat(this.value) * 100) / 100).toFixed(2);
$("#amount").val(num);
}
});
this.data.amountRequested = Math.round(parseFloat(amount) * 100) / 100;
}
...
You don't need jQuery for this action
You can achieve this using plain JavaScript, You can put this in the onKeyUp event.
Restrict - Special Characters
e.target.value = e.target.value.replace(/[^\w]|_/g, '').toLowerCase()
Accept - Number only
e.target.value = e.target.value.replace(/[^0-9]/g, '').toLowerCase()
Accept - Small Alphabet only
e.target.value = e.target.value.replace(/[^0-9]/g, '').toLowerCase()
I could write for some more scenarios but I have to maintain the specific answer.
Note It will work with jquery, react, angular, and so on.
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
if( $(this).val().indexOf('.') == 0){
$(this).val("");
}
//this is the simplest way
indexof is used to validate if the input started with "."
[User below code to restrict special character also
$(h.txtAmount).keydown(function (event) {
if (event.shiftKey) {
event.preventDefault();
}
if (event.keyCode == 46 || event.keyCode == 8) {
}
else {
if (event.keyCode < 95) {
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
}
else {
if (event.keyCode < 96 || event.keyCode > 105) {
event.preventDefault();
}
}
}
});]
Allow only numbers in TextBox (Restrict Alphabets and Special Characters)
/*code: 48-57 Numbers
8 - Backspace,
35 - home key, 36 - End key
37-40: Arrow keys, 46 - Delete key*/
function restrictAlphabets(e){
var x=e.which||e.keycode;
if((x>=48 && x<=57) || x==8 ||
(x>=35 && x<=40)|| x==46)
return true;
else
return false;
}
/**
* Forbids special characters and decimals
* Allows numbers only
* */
const numbersOnly = (evt) => {
let charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode === 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
let inputResult = /^[0-9]*$/.test(evt.target.value);
if (!inputResult) {
evt.target.value = evt.target.value.replace(/[^a-z0-9\s]/gi, '');
}
return true;
}
In HTML:
<input type="text" (keypress)="omitSpecialChar($event)"/>
In JS:
omitSpecialChar(event) {
const keyPressed = String.fromCharCode(event.keyCode);
const verifyKeyPressed = /^[a-zA-Z\' \u00C0-\u00FF]*$/.test(keyPressed);
return verifyKeyPressed === true;
}
In this example it is possible to type accents.
$(document).ready(function() {
$('#Description').bind('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9 .]/gi,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
if (!(checkEmpty($("#Description").val()))) {
$("#Description").val("");
} //1Apr2022 code end
});
$('#Description').on('change', function() {
if (!(checkEmpty($("#Description").val()))) {
$("#Description").val("");
} //1Apr2022 code end
});
});
function checkEmpty(field) { //1Apr2022 new code
if (field == "" ||
field == null ||
field == "undefinied") {
return false;
} else if (/^\s*$/.test(field)) {
return false;
} else {
return true;
}
}
A more enhanced form would be
$('input[type=text]').on('input', function() {
var c = this.selectionStart,
r = /[^a-z ]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
Because it will allow you to enter space as well and it will only target the input fields with type text and wont bother the other input fields like email, password etc as normally we need special characters in email and password field

Javascript limit text field to positive and negative numbers

There'a way in javascript to allow the user input in a text field (input type="text") only digits but optionally having the minus before them? (I.e. only negative and positive number)
<input type='text' onkeypress='return numbersOnly(this,event,false,true);'>
function numbersOnly(Sender,evt,isFloat,isNegative) {
if(Sender.readOnly) return false;
var key = evt.which || !window.event ? evt.which : event.keyCode;
var value = Sender.value;
if((key == 46 || key == 44) && isFloat){
var selected = document.selection ? document.selection.createRange().text : "";
if(selected.length == 0 && value.indexOf(".") == -1 && value.length > 0) Sender.value += ".";
return false;
}
if(key == 45) { // minus sign '-'
if(!isNegative) return false;
if(value.indexOf('-')== -1) Sender.value = '-'+value; else Sender.value = value.substring(1);
if(Sender.onchange != null) {
if(Sender.fireEvent){
Sender.fireEvent('onchange');
} else {
var e = document.createEvent('HTMLEvents');
e.initEvent('change', false, false);
Sender.dispatchEvent(e);
}
}
var begin = Sender.value.indexOf('-') > -1 ? 1 : 0;
if(Sender.setSelectionRange){
Sender.setSelectionRange(begin,Sender.value.length);
} else {
var range = Sender.createTextRange();
range.moveStart('character',begin);
range.select();
}
return false;
}
if(key > 31 && (key < 48 || key > 57)) return false;
}
Related question: HTML Text Input allow only Numeric input
You can bind a listener (in javascript, that is) to the onKeyUp event (or the one that best fits your needs) and check what is the user trying to insert. Then you can decide if you'll let him insert that character or not.
NOTE: You'll want to control also the copy/paste event as the user could paste some text instead of writing it!
Use this. It works.
https://raw.github.com/SamWM/jQuery-Plugins/master/numeric/jquery.numeric.js
$(document).ready(function(){
$(".numeric").numeric({negative :true});
});​
Try the following regexp:
/^-?\d+$/
This is the best solution I came up with for positive and negative integers only
<input type="text" onkeyup="this.value = (this.value[0] === '-') ? ('-' + this.value.replace(/[^0-9]/g, '')) : (this.value.replace(/[^0-9]/g, ''));" pattern="^-?\d+" />
You can check it out here http://jsfiddle.net/4g08ofz6/
The pattern
pattern="^-?\d+"
is just an extra layer of validation for when the value is pasted in or dragged in but remember you should still always validate on the server site

jquery only allow input float number

i'm making some input mask that allows only float number. But current problem is I can't check if multiple dots entered. Can you check those dots and prevent it for me?
Live Code: http://jsfiddle.net/thisizmonster/VRa6n/
$('.number').keypress(function(event) {
if (event.which != 46 && (event.which < 47 || event.which > 59))
{
event.preventDefault();
if ((event.which == 46) && ($(this).indexOf('.') != -1)) {
event.preventDefault();
}
}
});
You can check for the period in the same statement.
Also, you need to use the val method to get the value of the element.
Also, you want to check for the interval 48 to 57, not 47 to 59, otherwise you will also allow /, : and ;.
jQuery(document).ready(function() {
$('.float-number').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
Enter Number:
<input type="text" name="number" value="" class="float-number">
</body>
</html>
I think you guys have missed the left right arrows, delete and backspace keys.
$('.number').keypress(function(event) {
if(event.which == 8 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46)
return true;
else if((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
event.preventDefault();
});
I think everybody forgot the case of pasting text with the mouse, in which you can't detect the keystrokes, because there's none. Here's another approach I have been working on.
// only integer or float numbers (with precision limit)
// example element: <input type="text" value="" class="number" name="number" id="number" placeholder="enter number" />
$('.number').on('keydown keypress keyup paste input', function () {
// allows 123. or .123 which are fine for entering on a MySQL decimal() or float() field
// if more than one dot is detected then erase (or slice) the string till we detect just one dot
// this is likely the case of a paste with the right click mouse button and then a paste (probably others too), the other situations are handled with keydown, keypress, keyup, etc
while ( ($(this).val().split(".").length - 1) > 1 ) {
$(this).val($(this).val().slice(0, -1));
if ( ($(this).val().split(".").length - 1) > 1 ) {
continue;
} else {
return false;
}
}
// replace any character that's not a digit or a dot
$(this).val($(this).val().replace(/[^0-9.]/g, ''));
// now cut the string with the allowed number for the integer and float parts
// integer part controlled with the int_num_allow variable
// float (or decimal) part controlled with the float_num_allow variable
var int_num_allow = 3;
var float_num_allow = 1;
var iof = $(this).val().indexOf(".");
if ( iof != -1 ) {
// this case is a mouse paste (probably also other events) with more numbers before the dot than is allowed
// the number can't be "sanitized" because we can't "cut" the integer part, so we just empty the element and optionally change the placeholder attribute to something meaningful
if ( $(this).val().substring(0, iof).length > int_num_allow ) {
$(this).val('');
// you can remove the placeholder modification if you like
$(this).attr('placeholder', 'invalid number');
}
// cut the decimal part
$(this).val($(this).val().substring(0, iof + float_num_allow + 1));
} else {
$(this).val($(this).val().substring(0, int_num_allow));
}
return true;
});
Good for integer and float values. Plus, copy/paste clipboard event.
var el = $('input[name="numeric"]');
el.prop("autocomplete",false); // remove autocomplete (optional)
el.on('keydown',function(e){
var allowedKeyCodesArr = [9,96,97,98,99,100,101,102,103,104,105,48,49,50,51,52,53,54,55,56,57,8,37,39,109,189,46,110,190]; // allowed keys
if($.inArray(e.keyCode,allowedKeyCodesArr) === -1 && (e.keyCode != 17 && e.keyCode != 86)){ // if event key is not in array and its not Ctrl+V (paste) return false;
e.preventDefault();
} else if($.trim($(this).val()).indexOf('.') > -1 && $.inArray(e.keyCode,[110,190]) != -1){ // if float decimal exists and key is not backspace return fasle;
e.preventDefault();
} else {
return true;
};
}).on('paste',function(e){ // on paste
var pastedTxt = e.originalEvent.clipboardData.getData('Text').replace(/[^0-9.]/g, ''); // get event text and filter out letter characters
if($.isNumeric(pastedTxt)){ // if filtered value is numeric
e.originalEvent.target.value = pastedTxt;
e.preventDefault();
} else { // else
e.originalEvent.target.value = ""; // replace input with blank (optional)
e.preventDefault(); // retur false
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="numeric" value="" placeholder="insert value">
[2017-10-31] Vanilla.js
let el = document.querySelector('input[name="numeric"]');
el.addEventListener('keypress',(event) => {
let k = event.key,
t = isNaN(k),
sc = ['Backspace'].indexOf(k) === -1,
d = k === '.',dV = el.value.indexOf('.') > -1,
m = k === '-',mV = el.value.length > 0;
if((t && sc) && ((d && dV) || (m && dV) || (m && mV) || ((t && !d) && (t && !m)))){event.preventDefault();}
},false);
el.addEventListener('paste',(event) => {
if(event.clipboardData.types.indexOf('text/html') > -1){
if(isNaN(event.clipboardData.getData('text'))){event.preventDefault();}
}
},false);
<input type="text" name="numeric">
Your code seems quite fine but overcomplicated.
First, it is $(this).val().indexOf, because you want to do something with the value.
Second, the event.which == 46 check is inside an if clause that's only passed when event.which != 46, which can never be true.
I ended up with this which works: http://jsfiddle.net/VRa6n/3/.
$('.number').keypress(function(event) {
if(event.which < 46
|| event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46
&& $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
});
I found this way to do this,
$.validator.addMethod("currency", function (value, element) {
return this.optional(element) || /^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/.test(value);
}, "Please specify a valid amount");
https://gist.github.com/jonkemp/9094324
HTML
<input type="text" onkeypress="return isFloatNumber(this,event)" />
Javascript
function isFloatNumber(item,evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode==46)
{
var regex = new RegExp(/\./g)
var count = $(item).val().match(regex).length;
if (count > 1)
{
return false;
}
}
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
jsfiddle.net
Using JQuery.
$(document).ready(function()
{
//Only number and one dot
function onlyDecimal(element, decimals)
{
$(element).keypress(function(event)
{
num = $(this).val() ;
num = isNaN(num) || num === '' || num === null ? 0.00 : num ;
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
{
event.preventDefault();
}
if($(this).val() == parseFloat(num).toFixed(decimals))
{
event.preventDefault();
}
});
}
onlyDecimal("#TextBox1", 3) ;
});
One-more plugin, based on Carlos Castillo answer
https://github.com/nikita-vanyasin/jquery.numberfield.js
Adds method to jQuery object:
$('input.my_number_field').numberField(options);
where options is (you can pass any or no options):
{
ints: 2, // digits count to the left from separator
floats: 6, // digits count to the right from separator
separator: "."
}
Using jQuery and allowing negative floats :
// Force floats in '.js_floats_only' inputs
$(document).ready(function() {
$('.js_floats_only').each(function() {
// Store starting value in data-value attribute.
$(this).data('value', this.value);
});
});
$(document).on('keyup', '.js_floats_only', function() {
var val = this.value;
if ( val == '-' ) {
// Allow starting with '-' symbol.
return;
} else {
if ( isNaN(val) ) {
// If value is not a number put back previous valid value.
this.value = $(this).data('value');
} else {
// Value is valid, store it inside data-value attribute.
$(this).data('value', val);
}
}
});
For simple cases and without hardcoding some html instructions would fit that pretty enough
<input type="number" step="0.01"/>
$('.number').keypress(function(event){
if($.browser.mozilla == true){
if (event.which == 8 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 9 || event.keyCode == 16 || event.keyCode == 46){
return true;
}
}
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
This works in all browsers.
<input type="text" data-textboxtype="numeric" />
<script>
$(document).on('keydown', '[data-textboxtype="numeric"]', function (e) {
// Allow: backspace, delete, tab, escape, enter and . and -
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190, 109, 189]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return true;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
return false;
}
return true;
});
</script>
Below Code I am allowing only Digits and Dot symbol.
ASCII characters number starts in 47 and ends with 58 and dot value is 190.
$("#Experince").keyup(function (event) {
debugger
if ((event.which > 47
&& event.which < 58) ||event.which== 190) {
if ($("#Experince").val().length > 3) {
}
} // prevent if not number/dot
else {
$("#Experince").val($("#Experince").val().slice(0, -1))
}
});

Categories