JQuery to allow only alphabets, numeric and forward slash in TextBox - javascript

I have a text field in ASP.NET and i want to allow only alphanumeric and forward slash (/) keys in that. I tried the following code,
function jsCheckInput(e) {
var evt = (e) ? e : window.event;
var key = (evt.keyCode) ? evt.keyCode : evt.which;
if (key != null) {
key = parseInt(key, 10);
if (key < 47 || (key > 57 && key < 65) || (key > 90 && key < 97) || key > 122) {
if (!jsIsUserFriendlyChar(key)) {
return false;
}
}
else {
if (evt.shiftKey) {
return true;
}
}
}
return true;
}
function jsIsUserFriendlyChar(val) {
// Backspace, Tab, Enter, Insert, and Delete
if (val == 8 || val == 9 || val == 13 || val == 45 || val == 46) {
return true;
}
// Ctrl, Alt, CapsLock, Home, End, and Arrows
if ((val > 16 && val < 21) || (val > 34 && val < 41)) {
return true;
}
return false;
}
In the web forms page i added like below,
<asp:TextBox ID="text_value" CssClass="textbox" onkeydown="return jsCheckInput(event);" runat="server"></asp:TextBox>
Here i am able to enter alphabets and numbers but i am not able to enter the value /. I have enabled the shift key so i can give shift + ? to enter the forward slash. Also another problem is when i press shift + any numeric key the special characters there like ! # # $ % ^ & * ( ) ... are also coming in tet field. What am i doing wrong here?

if you want to use Regular Expression. Ignore if you don't
const regex = /^[a-z0-9\/]+$/gi;
const str = `asdasdas/asdfaASDASDA`; //test string
if(regex.test(str )){
console.log('Allowed'+str);
}
Tested here

You don't need shift key to type forward slash. Key code for forward slash(/) is 191. Just add this also in your if condition.
function jsCheckInput(e) {
var evt = (e) ? e : window.event;
var key = (evt.keyCode) ? evt.keyCode : evt.which;
if (key != null) {
key = parseInt(key, 10);
if (key < 47 || (key > 57 && key < 65) || (key > 90 && key < 97) || key > 122 || key != 191) {
if (!jsIsUserFriendlyChar(key)) {
return false;
}
}
}
return true;
}

SOLUTION
Finally found a solution as below,
function jsCheckInput(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || (charCode > 46 && charCode < 58))
return true;
else if (jsIsUserFriendlyChar(charCode))
return true;
else
return false;
}
catch (err) {
alert(err.Description);
}
}
This code works perfectly!!

Related

jQuery prevent writing letters and change comma to dot

I have tried to modify this code but it just wont work...probably some small mistake but i can't debug it :(
// replace , with . and block writing letters
$(document).on("keydown", ".amount", function () {
$(this).keydown(function(e) {
if(e.keyCode==188 || e.keyCode==110 || e.keyCode==108){
e.preventDefault();
$(this).val($(this).val() + '.');
}
var key = e.charCode || e.keyCode || 0;
return (key == 8 || key == 9 || key == 46 || key == 110 || key == 188 || key == 190 || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});
};
This is original code and it doesn't work on dynamic content
that is why i want to modify it!
How about just calling your ForceNumericOnly method when the user clicks into an input with .amount?
$(document).on('focus', '.amount', function(){
$(this).ForceNumericOnly();
});
https://jsfiddle.net/daveSalomon/r5n8xuhx/5/
You could (should) optimise it so it doesn't add the keydown handler again if it's already run the ForceNumericOnly code... something like:
$.fn.ForceNumericOnly = function() {
return this.each(function() {
if($(this).data('forceNumberOnly'){ return; }
$(this).data('forceNumberOnly',true);
...
});
};
https://jsfiddle.net/daveSalomon/r5n8xuhx/6/
There's no JS required - just use a number input:
<input class="amount" type="number">

Restrict to 2 decimal places in keypress of a text box?

I want to enter a decimal point in a text box. I want to restrict the user by entering more than 2 digits after the decimal point. I have written the code for achieving that in the Keypress event.
function validateFloatKeyPress(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
if (charCode == 46 && el.value.indexOf(".") !== -1) {
return false;
}
if (el.value.indexOf(".") !== -1)
{
var range = document.selection.createRange();
if (range.text != ""){
}
else
{
var number = el.value.split('.');
if (number.length == 2 && number[1].length > 1)
return false;
}
}
return true;
}
<asp:TextBox ID="txtTeamSizeCount" runat="server" onkeypress="return validateFloatKeyPress(this,event);" Width="100px" MaxLength="6"></asp:TextBox>
The code is working but the issue is: if I enter ".75" and then change it to "1.75", it is not possible. Only way to do it is delete it completely and then type "1.75". This issue occurs if there are already 2 digits after decimal in the textbox. The conditions that I impose are
a) After decimal is present, it must at least have 1 or 2 digits. For ex .75 or .7 or 10.75 or 333.55 or 333.2 is accepted. but not .753 or 12.3335
b) Before the decimal, it not a must for the user to enter a value. User must also be able to enter integer numbers also.
Can you tell me what could be the issue?
Thanks,
Jollyguy
You were almost there. Just check that there are no more than 2 characters after the decimal.
UPDATE 1 - check carat position to allow character insertion before the decimal.
UPDATE 2 - correct issue pointed out by ddlab's comment and only allow one dot.
function validateFloatKeyPress(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
//just one dot (thanks ddlab)
if(number.length>1 && charCode == 46){
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(".");
if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
return false;
}
return true;
}
//thanks: http://javascript.nwbox.com/cursor_position/
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', o.value.length)
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text)
} else return o.selectionStart
}
http://jsfiddle.net/S9G8C/1/
http://jsfiddle.net/S9G8C/203/
Consider leveraging HTML5's Constraint Validation API. It doesn't necessarily prevent typing invalid values, but the field is marked invalid and it halts submission of the <form> (by default). I added the <output> to illustrate why the browser considers e.g. "1.100" a valid value (it sees the numeric value as "1.1").
<input id="n" type="number" step=".01">
var
n = document.getElementById('n'),
o = document.getElementById('o'),
didInputN = function(e) {
o.value = n.valueAsNumber;
};
n.addEventListener('input', didInputN);
input:invalid {
color: white;
background-color: red;
}
<input id="n" type="number" step=".01">
<output id="o" for="n"></output>
Philosophically, you might consider this a more usable approach as it allows the user to paste an invalid entry and edit it directly in the field.
You can do it by another way with onchange event, to not restrict to user to type, rather just convert number after typing, to make uniform, like this,
function validateFloatKeyPress(el) {
var v = parseFloat(el.value);
el.value = (isNaN(v)) ? '' : v.toFixed(2);
}
<input id="aninput" type="text" onchange="validateFloatKeyPress(this);" />
45.846 should be 45.85 but in your code user needed to convert their-self and then they will type 45.85 directly
1.)No multiple decimals points.
2.)Two numbers after decimal point.
3.)Allow only Numbers and one decimal point(.).
This will help.jsFiddle
function decimalValidation(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split('.');
if(charCode == 8) {
return true;
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
//just one dot
if(number.length>1 && charCode == 46){
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(".");
if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
return false;
}
return true;
}
function getSelectionStart(o) {
return o.selectionStart
}
Hi #webvitaly The above code will work in IE too please check
And backspace after decimals not working in Mozilla i updated my answer.
this code is very complet, I change "." to ",":
can't "," in begin
can't write more ","
<script type="text/javascript">
function isNumberKey(evt, el) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split(',');
var caracter = el.value;
if (charCode != 44 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
if (charCode == 44 && caracter == "") {
return false;
}
if (charCode == 44 && caracter.indexOf(",") != -1) {
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(",");
if (caratPos > dotPos && dotPos > -1 && (number[1].length > 1)) {
return false;
}
return true;
}
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', o.value.length)
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text)
} else return o.selectionStart
}
</script>
My problem was that I need it to show an error message in real time if the user is allowed only 2 decimals:
value = parseFloat(valueFromInput);
parseFloat(value.toFixed(2)) !== value // condition to check
The above code worked for me..toFixed converts the float to a string wit only 2 decimals and I have to convert back to float to check with the initial value if are the same.
P.S. And before this condition you should check if the value is NaN.

Javascript for AlphaNumeric and Uppercase typing

i have coded javascript for AlphaNumeric. Also if user type lower case then it convert into uppercase. Converting from lower case to upper case obj.value = String.fromCharCode(key).toUppercase(); not working properply. Please help me to sort out it. Thanks in advance..
function isAlphaNumeric(e, obj, index) {
var key;
if (window.event) {
key = window.event.keyCode; //IE
obj.value = String.fromCharCode(key).toUpperCase();
} else {
key = e.which; //firefox
obj.value = String.fromCharCode(key).toUpperCase();
}
if (!((key > 64 && key <= 90) || (key > 96 && key <= 122) || (key > 47 && key <= 57) || (key == 8) || (key == 0) || (key == 127))) {
alert(" Enter only Alpha-Numeric value in this field. ");
setTimeout(function () {
clearField(obj)
}, 500);
return false;
}
}
Mate check out my answer:
$('textarea').bind('keydown keypress keyup', function (e) {
var replacedText = $(this).val().replace(/[^A-Z0-9]/g, function (match) {
if (match != undefined) {
return match.toUpperCase();
}
});
$(this).val(replacedText);
});
Here is the DEMO
You should use .toUpperCase() instead of .toUppercase() as Javascript is case sensitive.
http://www.w3schools.com/jsref/jsref_touppercase.asp

Need to replace "comma" with 'dot'

Please help me to adjust an existing script to replace COMMA with DOT.
I use a script which limit the inserting character into Text fields. Only 1,2,3,4,5,6,7,8,9,0 and "." and "," are accepted to be inserted. I would like to have two buttons of inserting DOT - key==188 (comma) and key== 190 (dot).
jQuery.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 110 ||
key == 188 ||
key == 190 ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
});
};
$("#iMONEY").ForceNumericOnly();
It can be tested HERE
Just use
if(e.keyCode == 188){
e.preventDefault();
$(this).val($(this).val() + '.');
}
Here you go. :)
For future references Mini-Tutorial.
The value of the textbox is updated after keypress event is fired. It's not a place to replace comma with dot. Use keyup event instead:
jQuery.fn.ForceNumericOnly =
function()
{
this.keyup(function(e)
{
// console.log("Change");
$(this).val($(this).val().replace(/,/g,"."));
});
};
$("#iMONEY").ForceNumericOnly();
DEMO
var key = e.charCode || e.keyCode || 0;
// 110 is numpad comma code
if (key === 188 && key === 110) {
e.preventDefault();
$(this).val($(this).val() + '.');
}
You need to use the Replace method
var someVariable = "1,2,3,4,5,6,7,8,9,0";
$mylabel.text( someVariable.replace(',', '.') );
EDIT:
If you are checking from TextBox then do it like this:
if(Key == 188){
var someVariable = $("#TEXTBOXID").val();
somVariable = someVariable.replace(',', '.');
}

using jQuery/javascript to restrict price field input

I found the following jQuery code on the internet, but I soon found that it had a deficiency in that it dit not accept a decimal point (ascii code 46) - even though the code appears to allow it.
Currently, I cannot enter prices like 1.23, since the the period is ignored and I get 123 instead.
Can anyone spot whty this is not working?
// Numeric only control handler
$.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
})
};
I am using the plugin like this:
$(function(){
$('#price_field').ForceNumericOnly();
});
The other users have pretty much answered your question already, but I wanted to provide you with this link.
http://unixpapa.com/js/key.html
I found it quite useful when dealing with keyboard events and making them cross-browser compatible.
I hope this helps.
Just add the . (code 190 and 110) to the checks:
// Numeric only control handler
$.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 190 || // normal .
key == 110 || // keypad .
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
})
};
You should add the key code 190 to accept "."
// Numeric only control handler
$.fn.ForceNumericOnly = function() {
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow dot, backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 190 ||
key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
})
};
You need to include 190 and 110 for both decimal points.
// Numeric only control handler
$.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 190 || //add this line. 190 is the keycode for a period
key == 110 || //and this line. 110 is the keycode for a decimal
key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
})
};

Categories

Resources