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
Related
I have a working script to replace non alphanumerical letters from the text input. If you add special chars to text input, it doesnt let you to add to there. However, I want this script delete the special char after you add the letter, means that you can see the letter there but just after that it hs been removed (like when you try to upvote your own question on stackoverflow)
$("#nick").on("keypress", function(event) {
var englishAlphabetAndWhiteSpace = /[A-Za-z]/g;
var key = String.fromCharCode(event.which);
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39 || englishAlphabetAndWhiteSpace.test(key)) {
return true;
}
return false;
});
What is the correct way to do it ?
You want to show the letter and then remove it, use 'keyup' event
$('#test').on('keyup keypress', function(e) {
var reg = /[A-Za-z]/;
var value = $(this).val();
if (value && !reg.test(value[value.length - 1])) {
$(this).val(value.slice(0, value.length - 1));
}
})
Code on jsfiddler
You can use regex that'll replace all the non-alphabetic characters in the input value.
Use HTML5 pattern attribute on input to give regex
Use keyup and input event handlers to capture events
Use negated class regex to remove all non-alphabet symbols
Use setTimeout to clear the special characters after a delay
var timeout;
$("#nick").on("keypress input", function(e) {
var keyCode = e.keyCode || e.which; // Browser-independant
// If left or right arrow, then don't do anything
if (keyCode === 8 || keyCode === 37 || keyCode === 39) {
return true;
}
var $this = $(this); // Cache this
clearTimeout(timeout); // Clear previous timeouts
timeout = setTimeout(function() {
$this.val($this.val().replace(/[^A-Za-z]/g, ''));
}, 500);
});
input:valid {
color: green;
}
input:invalid {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="nick" pattern="[A-Za-z]+" />
Regex Explanation:
The regex on pattern, [A-Za-z]+ only matches one or more of the alphabet characters both uppercase and lowercase.
If I read it correctly, you are talking about inserting a delay before the invalid character vanishes?
It's a bit trickier as there is the clause of how long you want to see it before it vanishes & also what if you are faster than typing the next letter before it does.
After taking care of these, it should look something like this :
var removelast = false, remover;
var nick = $("#nick").on("keypress", function(event) {
function remove() {
nick.val(nick.val().slice(0,-1));
removelast = false;
}
clearTimeout(remover);
if(removelast) remove();
var englishAlphabetAndWhiteSpace = /[A-Za-z]/g;
var key = String.fromCharCode(event.which);
var allowed = event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39 || englishAlphabetAndWhiteSpace.test(key);
if (!allowed) {
removelast = true;
remover = setTimeout(remove, 100);
}
return true;
});
<input type="text" id="nick" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My requirement is to not allow user to type in any Alphabets. The below code allows 1 character to be entered even though I have provided the e.preventDefault() method on both keydown and keyup methods.
$(function() {
// Regular Expression to Check for Alphabets.
var regExp = new RegExp('[a-zA-Z]');
$('#test').on('keydown keyup', function(e) {
var value = $(this).val();
// Do not allow alphabets to be entered.
if (regExp.test(value)) {
e.preventDefault();
return false;
}
}); // End of 'keydown keyup' method.
}); // End of 'document ready'
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" name="test" />
What am I doing wrong? Is there some other way to get this done?
Replace
var value = $(this).val();
by
var value = String.fromCharCode(e.which) || e.key;
After all, you need to check which key has been pressed before allowing a character to be typed into the field.
Also, make sure the backspace and delete buttons and arrow keys aren’t blocked!
$(function() {
var regExp = /[a-z]/i;
$('#test').on('keydown keyup', function(e) {
var value = String.fromCharCode(e.which) || e.key;
// No letters
if (regExp.test(value)) {
e.preventDefault();
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" name="test" />
If your goal is to only accept numbers, dots and commas use this function instead:
$(function() {
var regExp = /[0-9\.\,]/;
$('#test').on('keydown keyup', function(e) {
var value = String.fromCharCode(e.which) || e.key;
console.log(e);
// Only numbers, dots and commas
if (!regExp.test(value)
&& e.which != 188 // ,
&& e.which != 190 // .
&& e.which != 8 // backspace
&& e.which != 46 // delete
&& (e.which < 37 // arrow keys
|| e.which > 40)) {
e.preventDefault();
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" name="test" />
You need to store input data somewhere and update it each time user inputs allowed character or reset when disabled
$(function() {
// Regular Expression to Check for Alphabets.
var regExp = new RegExp('[a-zA-Z]'),
inputVal = '';
$('#test').on('keydown keyup', function(e) {
var value = $(this).val();
// Do not allow alphabets to be entered.
if (regExp.test(value)) {
$(this).val(inputVal)
}
else{
inputVal = value
}
}); // End of 'keydown keyup' method.
}); // End of 'document ready'
Create a function that will mask it out
jsfiddle
$.fn.noMask = function(regex) {
this.on("keypress", function(e) {
if (regex.test(String.fromCharCode(e.which))) {
return false;
}
});
}
$("input").noMask ( /[a-zA-Z]/ );
If you are trying for only alphabet with space you can try it:
$("#test").on("keypress keyup blur",function (event) {
$(this).val($(this).val().replace(/[^a-zA-Z ]/, ""));
if (!((event.charCode > 64 &&
event.charCode < 91) || event.charCode ==32 || (event.charCode > 96 &&
event.charCode < 123))) {
event.preventDefault();
}
});
This code will allow only numbers to be accepted for example in a telepone number input field. This is the improvement on the accepted answer.
var regExp = /[0-9]/;
$("#test").on('keydown keyup blur focus', function(e) {
var value =e.key;
/*var ascii=value.charCodeAt(0);
$('textarea').append(ascii);
$('textarea').append(value);
console.log(e);*/
// Only numbers
if (!regExp.test(value)
&& e.which != 8 // backspace
&& e.which != 46 // delete
&& (e.which < 37 // arrow keys
|| e.which > 40)) {
e.preventDefault();
return false;
}
});
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
}
I have checked other questions here at SO, however they do not answer my question. I want to simply catch certain keyCode and replace it with another. I am working with characters, not white spaces, and I do not need to loose focus or the like.
Below is my code. But you can replace those keyCodes with your (eg. when capital "A" is pressed, it should replace with zero 0, etc.). The idea is to replace the keyCode.
phrase.keypress(function(event)
{
if (event.shiftKey)
{
switch (event.keyCode)
{
// Cyrillic capitalized "Н" was pressed
case 1053: event.keyCode = 1187; event.charCode = 1187; event.which = 1187; break;
// Cyrillic capitalized "О" was pressed
case 1054: event.keyCode = 1257; event.charCode = 1257; event.which = 1257; break;
// Cyrillic capitalized "У" was pressed
case 1059: event.keyCode = 1199; event.charCode = 1199; event.which = 1199; break;
}
}
});
I tried with keydown and keyup as well. They do not alter the keyCode. How can I do that?
P.S. If possible, I am looking for a solution which does not "event.preventDefault() and manually insert desired key to input field, then move cursor to the end". I want cleaner and "right" solution. Thank you.
Keyboard event properties are all READ-only. You cannot capture one keyCode and change it to another.
See reference from MDN - Keyboard Events - All are read only can't be set.
As you mentioned in your post. -- If you wan't to handle, then you have to stop browser default key press and set the desired value to the element yourself.
While the properties on the KeyboardEvent instance is READ ONLY, you can override KeyboardEvent's prototype and create a getter for whatever you want to change. Here is an example which changes the keycodes of hjkl to act like arrow keys.
Object.defineProperty(KeyboardEvent.prototype, 'keyCode', {
get: function() {
switch (this.key) {
case 'h': return 37; // left
case 'j': return 40; // down
case 'k': return 38; // up
case 'l': return 39; // right
default: return this.which
}
}
})
I am using the following code to achieve the same result as if I had changed the keyCode, without actually being able to change it.
function inputValidation() {
var srcField = event.srcElement;
var sKey = event.keyCode;
var inputLetter = String.fromCharCode(sKey);
if (typeof(srcField) !== "undefined" && srcField !== null) {
inputLetter = transformInput(inputLetter);
var caretPos = srcField.selectionStart;
var startString = srcField.value.slice(0, srcField.selectionStart);
var endString = srcField.value.slice(srcField.selectionEnd, srcField.value.length);
srcField.value = startString + inputLetter + endString;
setCaretPosition(srcField, caretPos+1); // '+1' puts the caret after the input
event.preventDefault ? event.preventDefault() : event.returnValue = false; //for IE8
}
}
srcField.selectionStart gives the starting position of the text you have selected and srcField.selectionEnd gives the end position of the selection, if you haven't selected any text srcField.selectionStart equals srcField.selectionEnd.
The function setCaretPosition came from this answer by kd7. I only changed it to make it receive the element instead of its Id
function setCaretPosition(elem, caretPos) {
if (elem != null) {
if (elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
} else {
if (elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
} else
elem.focus();
}
}
}
you can change value as manuel and handle keypress. if you want to check key declare a variable and check your keycode.
this.event.target.value = this.event.target.value + ".";
return false;
full code:
function isNumberKeyDec(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var apos = 0;
if (charCode == 44) {
apos = 1;
charCode = 46;
}
if (this.event.target.value.length == 0 && charCode == 46) {
return false;
}
if (this.event.target.value.length == 1 && this.event.target.value == "0" && charCode == 48) {
return false;
}
if (this.event.target.value.length == 1 && this.event.target.value == "0" && charCode != 46) {
this.event.target.value = "";
}
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46) {
return false;
}
if (charCode == 46 && this.event.target.value.indexOf(".") != -1) {
return false;
}
if (this.event.target.value.indexOf(".") != -1) {
if (this.event.target.value.substring(this.event.target.value.toString().indexOf(".")).length >= 2) {
return false;
}
}
if (this.event.target.value.indexOf(".") == -1 && charCode != 46) {
if (this.event.target.value.length >= 3 && charCode != 46) {
return false;
}
}
if (apos == 1) {
this.event.target.value = this.event.target.value + ".";
return false;
}
return true;
}
I wanted a text field to take only numbers ans some control keys and number should be exactly four digit long, not less not more. My validation code is
function checkValidInput()
{
$(".validateYearTextBox").keydown(function(event)
{
// Allow only delete, backspace,left arrow,right arraow and Tab
if (
event.keyCode == 46 //delete
|| event.keyCode == 8 //backspace
|| event.keyCode == 37 //leftarow
|| event.keyCode == 39 //rightarrow
|| event.keyCode == 9 //tab
)
{
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode <96 ||event.keyCode > 105) ) {
event.preventDefault();
}
}
});
$(".validateYearTextBox").keyup(function(event)
{
var val = $(this).val();
if (val.length > 4){
alert ("Max length is 4");
val = val.substring(0, valore.length - 1);
$(this).val(val);
$(this).focus();
return false;
}
});
}
Here, my first validation is working, but my send one is not working.
I am calling this validation function in my aspx page like this
<script type="text/javascript">
$(document).ready(function(){
checkValidInput();
}
</script>
What is going wrong?
Simplify it:
function checkValidInput() {
// Allow only delete, backspace, left arrow, right arrow,
// Tab, ctrl+v and numbers
$(".validateYearTextBox").keydown(function(event) {
if (!((event.keyCode == 46 ||
event.keyCode == 8 ||
event.keyCode == 37 ||
event.keyCode == 39 ||
event.keyCode == 9) ||
(event.ctrlKey && event.keyCode == 86) || // Edit: Added to allow ctrl+v
$(this).val().length < 4 &&
((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105)))) {
// Stop the event
event.preventDefault();
return false;
}
});
// Edit: Added validate after copy+paste.
// This removes non-numeric characters and truncates the length
// to 4 if the user copy + pasted.
$(".validateYearTextBox").change(function(event) {
var value = $(this).val();
value = value.replace(/[^0-9]/g,'');
value = value.substr(0,4);
$(this).val(value);
});
}
$(document).ready(function() {
checkValidInput();
});
http://jsfiddle.net/nwellcome/687kD/
Edit: Personally I like the Masked Input jQuery plugin but that might be a heavy-handed solution if this is all you need to do.
There are many, many jQuery plugins that already do this in one form or another.
One that does mostly1 what you want is Masked Input Plugin. If you can, I recommend using something existing, working and proven, rather than reinventing.
1 The only part that it doesn't seem to do is display an error if a user tries to enter more than n characters but I'm sure you could modify the plugin or add a length check to the <input>
Use regular expression :
enter code here
function validator(elem,msg)
{
var exp=/^([0-9]+)$/; //it only allows for numbers
if(elem.value.match(exp))
{return true;}
else
{
alert(msg);
elem.focus();
return false;
}
}
the html code :
enter code here
<html><head>
<script src="javasript.js" type="text/javascript">
</head>
<body>
<form method=POST>
<input type='text' maxlength=4 name='num' id='num'>
<input type='submit' value=OK onClick="validator(document.getElementById('num'),'Only four numbers and numbers only!');">
</form> //the maxlength in input text tag restrict the maximum length of the input
</body></html>
Here's a simple way of doing it. Stores the old text before an event changes the text. Then check to see if the new text is valid or not. If it isn't, then revert back to the old text. To further ensure the maximum of 4 characters, add a maxlength attribute to all <input type="text"> elements.
jQuery.fn.forceNumericOnly = function() {
return this.each(function() {
var oldText;
$(this).keyup(function(e) {
var newText = $(this).val();
if (newText != "" && (isNaN(newText) || val.length > 4))
$(this).val(oldText);
else
oldText = $(this).val();
})
$(this).blur(function(e) {
var newText = $(this).val();
if (newText != "" && (isNaN(newText) || val.length > 4))
$(this).val(newText = oldText);
else
oldText = $(this).val();
});
})
};
$(".validateYearTextBox").forceNumericOnly();
if (document.ExamEntry.examnum.value=="") {
msg+="You must enter your examination number \n";
document.ExamEntry.examnum.focus();
document.getElementById('examnum').style.color="red";
result = false;
}
$('.numeric').keypress(function(e) {
var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
if (verified || e.delegateTarget.value.length>3 || e.ctrlKey ==true) { if(e.which!=8 ){e.preventDefault();}}
}).on('paste',function(e){ e.preventDefault();});
Here add class=numeric to input text box'. it will allow only 4 digits if you want to limit size to 2 digits change to e.delegateTarget.value.length>1 and so on as index starts from zero
Use HTML input maxlength attribute for this and also set the size value of fixing width 4 in same input size attribute.
<input type="text" maxlength="4" size="4">
Here is a simple answer that takes care of copy paste and all.
$(document).on("input", ".validateYearTextBox", function() {
var value = this.value
value = value.replace(/\D/g,'');
for (i = 0; i < value.length; i++) {
if (i > 3) {
value = value.replace(value[i], '')
}
}
});