how to block specific charter inputs in ASP.NET - javascript

i have the below asp.net code to get user input then using the below javascript i have make sure that it is not kept empty by the user. now what i want do is to block user input on few characters such as (|,#,#,$) using the same javascript. any suggestion on how can i do this?
<asp:TextBox ID="txtAccountName" runat="server" Width="100%" CssClass="input" Enabled="False" onblur="CheckTxtBox(this);"></asp:TextBox>
function CheckTxtBox(sender) {
if (sender.value == "") {
alert("Please enter Address 1");
return false;
}
}

Two ways you can do this
1) In "keypress" event.Check the user press a character like (|,#,#,$)then stop them right there
2) "onblur" event: when the input element loses focus, validate its contents. If the value is invalid, display a message
Note
the second method is better because if user is copy pasting the content then the first method will not catch them
First method
function CheckTxtBox(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (//charactercode of the keys as condition) {
return false;
}
return true;
};
Second Method
In your onblur event you can check your textbox value with a regular expression and validate it with regular expression.

function CheckTxtBox(e) {
var k;
document.all ? k = e.keyCode : k = e.which;
return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}
An your asp control :
<asp:TextBox ID="txtAccountName" runat="server" Width="100%" CssClass="input" Enabled="False" onkeypress="return CheckTxtBox(event)""></asp:TextBox>

To validate keys/text entered in edit controls, Regular Expressions are recommended. Have a look at: http://www.9lessons.info/2009/03/perfect-javascript-form-validation.html for demos on few such validation examples.
But, it is not a good practice to stop the validation with the browser alone. Always do a validation at the server end. This is due to the fact that JavaScript can be disabled in browsers, which can allow non-validated data posts to the server.

i did it here is what i did. now this takes only uppercase charters from (A-Z) and numbers from (1-9). thank everyone for your help. its much appreciated.
<asp:TextBox ID="txtAccountName" runat="server"
Width="100%" CssClass="input" Enabled="False" onkeypress="return isNumber(event);"></asp:TextBox>
// this JS validates and prevent inputting symbols
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 65 || charCode > 90) && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}

Related

onkeypress is not working with textbox in asp.net webform

onkeypress is not working with textbox in asp.net webform
I want to prevent special characters and alphabets
Following is the aspx
<wijmo:C1InputText ID="SAC" runat="server" Style="width: 150px; display: inline-block;" onkeydown="return onlyNumbers(this,event);">
</wijmo:C1InputText>
function onlyNumbers(txt, event) {
var charCode = (event.which) ? event.which : event.keyCode
if (charCode == 46) {
if (txt.value.indexOf(".") < 0)
return true;
else
return false;
}
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;
}
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode!=190)
return false;
return true;
}
It returns false but not preventing to enter.
If I replaced onkeypress with onkeydown it works
Please have a look on this post :
https://forums.asp.net/t/1888076.aspx?onKeyPress+vs+OnKeyDown+vs+OnKeyUp
this is the part of the answer you want :
OnKeyDown allows you to fire an event prior to the character being entered within the Textbox, so that you could check what the character being pressed is prior to determining if it should be allowed or not.
OnKeyUp will allow you to essentially hold a key down and will not fire an event until the key is released.
OnKeyPress will fire an event for each character key that is pressed (including those being held down).

Prevent keypress when Alt key plus number from Bloq number is pressed

I'm having problems avoiding the special chars (Alt + number from Bloq. num -> ☺☻♥♦♣♠•◘○)in an input.
My input is declared like this:
<html:text styleId="inputMaxVol" styleClass="numeric"/>
This is on my onReady
$(".numeric").keydown(function(event) {
return maskNumber();
});
And here is where I'm trying to do the job (with no success)
function maskNumber() {
if (event) {
var charCode = (event.which)? event.which : event.keyCode;
console.log(charCode);
// If not a number
if ((charCode < 47 || charCode > 58) && (charCode < 95 || charCode > 105)) {
console.log("not a number");
return false;
} else if (event.altKey) {
//No special characters admitted
console.log("Alt pressed");
return false;
}
} else {
return false;
}
}
If I press Alt + 1 (key "1" from the numeric pad) the white smiley face appears and in my log appears something like that
18
not a number
97
Alt pressed
I've tried too with the event.preventDefault() with no success. Any idea about where is my problem?
Thanks, I really appreciate any help you can provide.
UPDATE: As explained in comments the solution comes changing the keydown event for keypress and changing the charcode comparation numbers (Now is only if (charCode < 48 || charCode > 57) due to the numbers returned have changed too.
So the solution is as follows
$(".numeric").keypress(function(event) {
return maskNumber();
});
function maskNumber() {
if (event) {
var charCode = (event.which)? event.which : event.keyCode;
// If not a number
if (charCode < 48 || charCode > 57) {
return false;
}
} else {
return false;
}
}
Simple as that!
Try below code it will work on each browser or if you want to use library then visit this link: https://github.com/tzuryby/jquery.hotkeys
$("#txtmy").keypress(function(event) {
if (event.which.toString().length > 3) {
event.preventDefault();
return;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtmy"/>
Returning false will not disable the event.
You need to do an event.preventDefault(), which stops the event from happening, instead of returning false.
event.preventDefault();
The return false is working for an onbeforesubmit event, of a Form.

Allow only number in JS and verify past

I have this function that only allows number in keypress how can i change this function ou method to call, so when i do ctrl+v verify too the values?
function isNumberKey(evt, obj) {
var containsDot = obj.value.indexOf(".");
var nrDecimals = Decimals(obj.value, ".");
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode == 8 || charCode == 9) {
return true;
} else if (charCode > 31 && (charCode < 48 || charCode > 57)) {
if (charCode == 46 && containsDot < 0) {
return true;
}
return false;
}
if (nrDecimals > 2) {
return false;
}
return true;
}
I call it this way
onkeypress="return isNumberKey(event,this);"
If you only want numbers in your input, you could do something like this:
onkeyup="this.value = this.value.replace(/[^0-9]+/, '');"
This replaces all non-number characters from the value. This does about the same as your whole function does, plus it works with the paste.
You need to change onkeypress to onkeyup.
For the full solution you need to switch to more complex code. As one of the comment below says, you can rightclick->paste aswell. This will not catch that. You need to bind multiple event (keypress, keyup, click are examples of events) to that one input. If you're lucky, focus will catch it (if rightclick blurs it, and after paste it focusses).
you can use jQuery. Change the below code as per your requirement.
$(document).ready(function() {
$("#id")
.bind('copy', function(e) {
alert('copying!');
})
.bind('paste', function(e) {
alert('pasting!');
})
.bind('cut', function(e) {
alert('cut!');
});
});
If you want to use plane javascript. I think below will work, but not sure about the browser compatibility.
<input type="text" onpaste="callFunc()" />

Input text field that only accepts numbers AND the dash character

I'm using the commonly used Javascript function to allow only numbers to be inputted into a text field:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
I call this onkeypress and it prevents anything but numbers to display. I'm trying to alter it so it will allow me to also put dashes (-) into the text field. The dash keycode is 189 so I tried this:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode != 189 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
Thinking that the conditional statement would then accept the dash character but that didn't seem to work. Any ideas on why this would be? Thanks for your help!
If you're using the keypress event you need to use the character code 45 for dash/hyphen.
If you're using the keydown/keyup events then you need to use 109 and 189 to cover the minus key in the numeric keypad and the one (usually) located above the P key.
if (charCode != 46 && charCode != 45 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
Demo: http://jsfiddle.net/J6B7U/
If you have doubts about which keycode is which a console.log(charCode); in your function will help you debug.
(Note also that trapping a key event is not enough to prevent invalid data being entered, because the user may change the field using the browser's edit menu or drag'n'drop.)
try this
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode != 45 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
in html
<input type="text" onkeypress="return isNumberKey(event)">
You want to use the character code for the dash, which is 45, not the keycode.
this code for only number types
<input onkeypress="return isNumberKey(event);">
<script>
function isNumberKey(evt)
{
var t = (evt.which) ? evt.which : event.keyCode;
return !(t > 31 && (t < 48 || t > 57))
}
</script>
This came up when I was asking, so it might be worth adding here that keyCode and charCode are deprecated, as at this time.
A better way of adding the check or implementing an isNumberKey function that also accepts the '-' character could be:
const isNumberKey = (event: KeyboardEvent) =>
((event.key.length > 1) || event.key.match(/^\d|-$/))
This way, we check allow special keys do their function, while making sure only numbers are allowed when single character keys are pressed.
This doesn't work well with mobile devices. For example, Chrome on Android will bring up the number keypad rather than the full keyboard when the input type is set to "number". You could try using input type="tel" instead. It would allow numbers 0-9, the - and (). It would also bring up the dial pad on Android. Haven't tested on iPhone.

How can I restrict number of character input in a field with javascript or jquery?

I wrote a validation code for an input text field, which will take only numbers and some control keys. I took the help from stackoverclow :), So I am here again to take the help. My validation code is
$("#txtLevel1Year").keydown(function(event)
{
// Allow only backspace,delete,left arrow,right arraow and Tab
if ( event.keyCode == 46
|| event.keyCode == 8
|| event.keyCode == 37
|| event.keyCode == 39
|| event.keyCode == 9)
{
// 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();
}
}
});
Now let me tell you what I am looking for, first, I want to restrict this field to take exactly 4 digits.not less not more, the second one is about optimization.
The text field(s) where I want this validation to work is(are)
<asp:TextBox runat="server" ID="txtLevel1Year" Width="50px" TabIndex="13"></asp:TextBox>
<asp:TextBox runat="server" ID="txtLevel2Year" Width="50px" TabIndex="17"></asp:TextBox>
<asp:TextBox runat="server" ID="txtLevel3Year" Width="50px" TabIndex="21"></asp:TextBox>
<asp:TextBox runat="server" ID="txtLevel4Year" Width="50px" TabIndex="25"></asp:TextBox>
Here I can repeat the the validation code 4 times to make this work by grabing four different ids though the validation is exactly same. Can I do anything which can remove this repeatation? If My problem isw not clear to you, please let me know.
thanx all of you in advance.
This is the edited part of this question I have achieved the goal of optimazation by creatinf a CSS class and call it in the div where I place all the year text boxes. But My limit to make it exactly 4 digits yet to be solved. please help me.
I assume that your validation works. The trick will be to add a class for all textbox. Say the class name is
.validateTB
Then modify your script as follows
$(".validateTB").keydown(function(event)
{
// Allow only backspace,delete,left arrow,right arraow and Tab
if ( event.keyCode == 46
|| event.keyCode == 8
|| event.keyCode == 37
|| event.keyCode == 39
|| event.keyCode == 9)
{
// 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();
}
}
});
Note that only selector is changed in the script.
Remember that you can set <input maxlength="4"> in HTML as an easy solution to the half of the problem. However, this only prevents browser user from entering more than 4 characters, but you can avoid it programatically, by calling some JS function that sets longer value.
Try this: (no blinking, and no copy paste allowed):
$(".validate").keyup(function(event) {
var val = $(this).val();
if (val.length > 5) {
val = val.substring(0, 5);
$(this).val(val);
return false;
}
}).keypress(function(event) {
if ($(this).val().length > 4) {
return false;
}
});
http://jsfiddle.net/xEMzx/
Ok, first of to have your validation code to all the four fields you can use a class selector (after deining a calss for all your elements):
<asp:TextBox runat="server" class='validate'
$(".validate").keydown(function(event)
to check for length you could use a keyup event (which in my experience is better for this task)
$(".validate").keyup(function(event){
var val = $(this).val();
if (val.length > 4){
alert ("Max length is 4");
val = val.substring(0, val.length - 1);
$(this).val(val);
$(this).focus();
return false;
}
});
fiddle here: http://jsfiddle.net/a5BJX/

Categories

Resources