Validation for integer number - javascript

I have created one form.In that form,it put one textbox.That text box should take only integer not character or float.So I applied validation like this.Does it right?
var a = document.getElementById('textbox1').value;
var b = /^\d+$/;
If (a.search(b) == -1)
{
alert(Must be Interger);
return false;
}

Yes, that will work, unless it's allowed to take a negative integer, in which case you need to add -? (optional negative sign) before the \d

You can use this script for Integer validation .
var value = Number(intfield.value);
if (Math.floor(value) == value) {
// value is integer, do something based on that
} else {
// value is not an Integer, show validation alerts
}

This should work:
var textboxValue = document.getElementById('textbox1').value;
if (!textboxValue.test(/^\d+$/)){
alert('Must be Interger');
return false;
}
Its a good practice to put easy names to vars or you will be lost months later whan you review your code :D

Hi I think below answer will be the better so that you can implement multiple TextBoxes
<script>
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 45 || charCode > 57)) {
return false;
return true;
}
}
</script>
Thanks
Bhanu Prakash

Related

Problem with match function in javascript for numeric validation

I have written following function to restrict only numbers with the limit of 2 numbers (below 100).
The first part checks special charters and letters. I got stuck in else part.
And Now I am trying to restrict with only 2 digits numeric number (without decimal). But it doesn't work the logic in below code. I am not allowed to use input type =number in HTML. The html input type is text
$(".allownumericTwo").on("input", function (evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
else {
$(this).val($(this).val().match(\d{0,2});
}
return true;
});
The input event is not cancelable. It also doesn't have a value for key code. What you could do instead is to check if the value is valid and if not reset it to its previous value. You also need to enclose your regex pattern between slashes, i.e. /^\d{0,2}$/.
e.g.
var oldValue = $(".allownumericTwo").val();
$(".allownumericTwo").on("input", function(evt) {
if (this.value.length > 0 && this.value.match(/^\d{0,2}$/) == null) {
this.value = oldValue;
} else {
oldValue = this.value;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='allownumericTwo'>
you can use isNumeric()
if($(this).val().length < 3)
{
if($.isNumeric($(this).val())){
//do something
}
}
This May help.
Do remember the match returns an array.
function printFirstTwoNumbers(val) {
var regex = /^\d{0,2}/g;;
console.log(val.match(regex));
return true;
}
printFirstTwoNumbers('288.80');
printFirstTwoNumbers('2.80');
printFirstTwoNumbers('29898.80');
printFirstTwoNumbers('300');

Not allowing to add or update any numeric or decimal value once it reach upto two decimal

I need to restrict the user for following things:
1) only allow numeric
2) decimal upto 2 digits
3) allow - backspace, tab,delete buttons
Below code is working fine except one scenario,
Problem is, (Example) when textbox input reach as 6545.12 then after try to change the value as below 65457.12 or 7545.13 then it does not allow and just restrict me. (so, here, not allowing to add new digit or change the existing digit before . or after .)
Can any one please guide me how to solve this issue.
calling below function on keypress event of textbox.
function isNumber(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (
&& // “-” CHECK MINUS, AND ONLY ONE.
(charCode != 8) && (charCode != 9) && (charCode != 37) && (charCode != 39) &&
(charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57)) {
return false;
}
if ($(element).val().indexOf('.') != -1)
{
var index = $(element).val().indexOf('.');
var len = $(element).val().length;
var CharAfterdot = (len + 1) - index;
if (CharAfterdot <= 3) {
return true;
}
else {
return false;
}
}
return true;
}
You might consider including a library that implements input masking (that is, only allowing certain kinds of values to be entered into an input field). Using a library like https://github.com/RobinHerbots/jquery.inputmask you can specify a regular expression as a mask. An example regular expression that only allows numbers up to two decimal places would be [0-9]+(\.[0-9][0-9]?)?. After including the masking library you can either call the mask directly on the element or add a data-inputmask-regex property to your input. See https://github.com/RobinHerbots/jquery.inputmask#usage for more.
Short version: this is a hard problem and other people have already done the work.

Allow arrow keys in Regular Expression

I am performing alphanumeric validation and now I am doing that user can only enter an alphanumeric value and also allow alphanumeric values only while pasting. So I used the following regular expression
function OnlyAlphaNumeric(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if ((charCode > 32 && charCode < 48) || (charCode > 57 && charCode < 65) ||
(charCode > 90 && charCode < 97) || charCode > 122) {
return false;
}
else {
return true;
}
}
And for preventing the copy and paste,
function CPOnlyAlphaNumeric(evt) {
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}
These two functions are calling from the following onkeypress and onkeyup methods such that is given below as shown that
#Html.TextBoxFor(model => model.ProductName, new { #class = "form-
control", #onkeypress = "return OnlyAlphaNumeric(this);", #onkeyup=
"return CPOnlyAlphaNumeric(this);" })
This works for alphanumeric validation, but it doesn't allow the cursor to move left side for editing the text. So what will change I should do in my Regular Expression.
Your problem has nothing related to regular expressions.
When you press any key (including left/right arrow) you take value of input, replace all forbidden characters and set the value of the input. When last action is done it's the browser native behavior to move the cursor to the end of input.
You can check what is the pressed key and if it's left/right arrow to skip the manipulation of input value.
function CPOnlyAlphaNumeric(evt) {
var code = evt.which ? evt.which : event.keyCode;
// 37 = left arrow, 39 = right arrow.
if(code !== 37 && code !== 39)
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}
Demo
However this is not a good solution because it will result in a terrible behavior (you won't be able to use shift for mark, the cursor will be moved at the end after first typed letter in the middle of word etc..)
A better solution could be to 'clean' the input value let's say 500 ms after user stop typing.
var timeout = null;
function CPOnlyAlphaNumeric(evt) {
if(timeout)
clearTimeout(timeout);
timeout = setTimeout(function(){
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}, 500);
}
Demo
Please note that you need to add the validation on server side as well (and maybe before the form submit, because user can hit enter to submit the form before the 'cleaning' of input is triggered).
You can try this, it may solve your problem.
var regex = new RegExp("^[a-zA-Z0-9]+$");
var charCode =(typeof event.which == "number") ?event.which:event.keyCode
var key = String.fromCharCode(charCode);
if (!(charCode == 8 || charCode == 0)) {
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
Problem with keyDown event is that you cant suppress the display of keys in the textfield (only alpha numeric in my case). You can do it in only keyPress event. But you cant get navigation keys in keyPress event, you can only track them in KeyDown event. And some of the keys $,%, have the same e.which that arrow keys has in keypress event. which is causing issues for me to write the logic to allow arrow keys but restrict the text to only Alpha numeric. Here is the code I came up with. Working fine now.
onKeyPress: function(e){
var regex = new RegExp("^[a-zA-Z0-9\b ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
var allowedSpecialKeys = 'ArrowLeftArrowRightArrowUpArrowDownDelete';
var key = e.key;
/*IE doesn't fire events for arrow keys, Firefox does*/
if(allowedSpecialKeys.indexOf(key)>-1){
return true;
}
if (regex.test(str)) {
return true;
}
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
return false;
}

RegEx in Javascript to allow negative decimal input to a text field

I have a requirement wherein i need to allow plus/minus sign in the beginning followed by a decimal number which allows only one dot in it in a text field input in html.
Bascially the text field should allow normal integer numbers and decimal numbers and also negative integer and negative decimal numbers. The plus and minus sign should be allowed only in the beginning (first character) and it's optional. Also should allow any number of decimal places (ex: -12.12345 etc) but only one decimal (dot) in the entry.
Digits allowed are: 1, + 1, -1, .1, +1.1, -1.1, -.12, +.12, 123.4456, -123.345, +123.345 etc
Any help is highly appreciated.
I'm using below regex for the above requirement.
var integerOnly = /[\+\-0-9\.]/g;
and below script (which i obtained from some other thread with slight modification) to validate it .
function restrictInput(myfield, e, restrictionType, checkdot){
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
alert("1 " + character);
// if user pressed esc... remove focus from field...
if (code==27) { this.blur(); return false; }
//alert("2");
// ignore if the user presses other keys
// strange because code: 39 is the down key AND ' key...
// and DEL also equals .
if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
alert("3");
if (character.match(restrictionType)) {
alert("4");
if(checkdot == "checkdot" & '-' != character & '+' != character){
alert("5");
return !isNaN((myfield.value.toString()==''? '0':myfield.value.toString())+character );
} else {
return true;
}
} else {
return false;
}
}
}
Here is how the script is called.
<input type="text" id="db" width="3" value="" onkeypress="return restrictInput(this, event, integerOnly, 'checkdot');"/>
It works fine except for few cases like:
It allows +/- any place any number of times. My requirement is to allow only at the beginning.
I tried to modify the regex as below.
var integerOnly = /[\+\-]?[0-9\.]/g;
In that case, it doesn't match the expression. It doesn't reach alert 4.
One thing is it allows only one decimal places and not more than one.
Can someone help me to modify my regular expression so as to allow only +/- in the beginning and only once.
Thank you.
Instead of playing with regex, validate your text using isNumber function as follows
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
I think that you want something like this:
^[-+]?(\d+\.?|\d*\.\d+)$
As the digits before the decimal separator or the digits after are optional (e.g. 1. or .1) but noth both, you need to handle the cases separately.
var test_ary = ['1', '+1', '-1', '.1', '+1.1', '-1.1', '-.12', '+.12', '123.4456', '-123.345', '+123.345'];
var reg = /^[\+\-]?(?:\.?\d+|\d+\.?\d+)$/;
var i;
for ( i = 0; i < test_ary.length; i = i + 1) {
console.log(reg.test(test_ary[i]));
}
you can also try this, with test case :)
I took 'niksvp' script and modified a bit to meet my requirement.
The below script works for all types of +/- decimal numbers. ex: 1.1, +1.1, -1.1, .1, -.1, +.1, 1, -1, +1, 123.345, +123.345, -123.345 etc
function isNumber(myfield, e) {
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
var n = myfield.value.toString()==''? '0':myfield.value.toString();
// this is required to allow numbers of this format
// -1.1, + 1.1, .1, -.1, +.1 etc
if(n == '-' | n == '+' | n== '.') {
n +=0;
}
if(n.length > 1) {
n = n.toString() + character;
}
return !isNaN(parseFloat(n)) && isFinite(n);
}
Thanks to all for your help.

how to validate as well as restrict length of asp.net text box control in javascript for numeric data?

I want o validate asp.net text box control by using javascript for number entry only. And maxlength of data should be 3 digit. For this i used following script -
function isNumberKey(evt, obj) {
var charCode = (evt.which) ? evt.which : event.keyCode
var txt = obj.value.length;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
else {
if (txt < 3) {
return true;
}
else {
return false;
}
}
}
and html code is as follows --
<asp:TextBox ID="txtNoCall" runat="server" onkeypress="javascript:return isNumberKey(event,this);"></asp:TextBox>
It is validating for numeric entry. and restrict length for 3 digit. but problem is that after 3 digit when i'm pressing backsapce key then that time it is not working.
How to solve this?
thanks.
Using the inbuilt asp.net validators would be much easier and give you both server and client side validation
<asp:RegularExpressionValidator id="RegularExpressionValidator1"
ControlToValidate="txtNoCall"
ValidationExpression="\d{3}"
Display="Static"
ErrorMessage="Only 3 digits allowed"
EnableClientScript="True"
runat="server"/>
Note I haven't run this but I had a feeling that enableclientscript didnt work on the regex validators but msdn documentation doesnt seem to mention anything about it so maybe I'm wrong.
You can do something like
if ((txt == 3) && (charCode == 8)) {
obj.value = obj.value.toString().substring(0, txt-1);
}
Here is complete code.
function isNumberKey(evt, obj) {
var LIMIT = 3;
var charCode = (evt.which) ? evt.which : event.keyCode
var txt = obj.value.length;
if ((txt == LIMIT) && (charCode == 8)) {
obj.value = obj.value.toString().substring(0, txt-1);
}
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
else {
if (txt < LIMIT) {
return true;
}
else {
return false;
}
}
}
Set TextBox.MaxLength as per the documentation.
If you need it to be Multiline, check out Specifying maxlength for multiline textbox.
If you try and build this yourself, make sure you include Ctrl-V and Shift-Ins in your test scenarios (most solutions don't handle these well).
As well as this, you should build the server side to do the validation there. It is impossible to solve the problem completely client side (since the user could always hand craft their own POST, or disable javascript).

Categories

Resources