Problem with match function in javascript for numeric validation - javascript

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');

Related

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.

Trying to validate a function in HTML

For my html, I'm trying to validate a form with a postcode input.
But this input is not working (or not being recognized). For my postcode input, I want to text box to only accept numbers.
Postcode input:
var Postcode = document.forms["Rego"]["postcode"].value;
var e = Postcode;
var code = e.keyCode;
if (code > 47 && code < 58) || code == 40 || code == 41 || code == 43) {
return true;
}
alert("Invalid Postcode. Please enter numbers only.");
return false;
What am I doing wrong?
In your condition if in line 4 after 58 why you close the ) ???
You are doing quite a few things wrong. You are not setting an event handler, you are actually binding to the value in the input box. You have to first get the DOM element representing the text box, then bind an event handler to the DOM element. Try this:
var Postcode = document.getElementById('post');
Postcode.onclick = function(e) {
console.log(e);
var code = e.keyCode;
if (code > 47 && code < 58 || code == 40 || code == 41 || code == 43) {
return true;
}
alert("Invalid Postcode. Please enter numbers only.");
e.preventDefault()
return false;
}
Fiddle: http://jsfiddle.net/S47gV/
To only accept numbers, you can use (for HTML5):
<input type="number" name="whatever">
Plus, if you want to validate it with js (doing so in browser is not recommended as anyone can modify your js file and push the contents to the server) or server code, here's some insight:
Try to convert the string passed to the server into a number. For example, in python you can do: int(whatever). If the conversion fails, that means the string isn't a number.
Hope that helps :)
If you use HTML5 you can set this automatically.
<input type="number" name="quantity" min="47" max="58">
By using below code textbox/inputbox allow only numeric value
$j('#inputbox_id').keydown(function (e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 46) || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105))) {
e.preventDefault();
}
}
});
and if you want to set length of textbox/input box then set "maxlength=5"
I think i have found what you are doing wrong:
You are reading postcode value from input type and then comparing its keycode.
However‚ it may work only when your input has single number and when you type more characters in it your postcode variable becomes something for example 5436 and then when you use keycode function on this in wont work as expected.

Validation for integer number

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

Use JavaScript to allow only specific characters in HTML input

I have written some JavaScript and jQuery code that accepts only numeric input in a textbox.
But this is not enough; I need to limit the input to certain numbers.
This textbox needs to deal with SSN numbers (Swedish SSN), and it has to start with 19 or 20. I want to force it to start with these numbers, but I can't manage to limit it to these.
$('input.SSNTB').keydown(function (event) {
var maxNrOfChars = 12;
var ssnNr = $('input.SSNTB').val();
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105))) {
console.log("if-1");
event.preventDefault();
}
if (event.shiftKey == true) {
console.log("if-3");
event.preventDefault();
}
//rules to make sure the textbox starts with correct number
if (event.keyCode != 49 || event.keyCode != 50 || event.keyCode != 97 || event.keyCode != 98) {
console.log("if-4, Keycode:" + event.keyCode);
event.preventDefault();
}
}
});
The last if-case is executed to for testing this it is. It is executed as planed but it wont limit the input chars as its built for.
any tips or ideas?
You can use regex to limit the user to only inputting numbers and dashes. Using regex has the advantage that users can more naturally interact with the input, for instance they can paste into the text input and it will be validated successfully:
//bind event handler to the `keyup` event so the value will have been changed
$('.SSNTB').on('keyup', function (event) {
//get the newly changed value and limit it to numbers and hyphens
var newValue = this.value.replace(/[^0-9\-]/gi, '');
//if the new value has changed, meaning invalid characters have been removed, then update the value
if (this.value != newValue) {
this.value = newValue;
}
}).on('blur', function () {
//run some regex when the user un-focuses the input, this checks for the number ninteen or twenty, then a dash, three numbers, a dash, then four numbers
if (this.value.search(/[(20)(19)](-)([0-9]{3})(-)([0-9]{4})/gi) == -1) {
alert('ERROR!');
} else {
alert('GOOD GOING!');
}
});
Here is a demo: http://jsfiddle.net/BRewB/2/
Note that .on() is new in jQuery 1.7 and in this case is the same as using .bind().
Thought I would post the solution that came to the end. I actually kept the similar code that I posted above and did not covert this it RegExp. What was done was to verify the number after focus on this textbox is lost. It it is incorret the user will be informed and forced to fill in a valid number.
$('input.SSNTB').focusout(function () {
var ssnNr = $('input.SSNTB').val();
var ssnNrSub = ssnNr.substring(0, 2);
//console.log(ssnNrSub);
//checks for correct lenggth
if (ssnNr.length < 12) {
$('div.SSNHelp label.Help').html('SSN to short. Please fill in a complete one with 12 numbers');
setTimeout(function () {
$('input.SSNTB').focus();
}, 0);
validToSave = false;
return;
}
//checks so it starts correct
if (ssnNrSub != "19" && ssnNrSub != "20") {
$('div.SSNHelp label.Help').html('The SSN must start with 19 or 20. Please complete SSN.');
setTimeout(function () {
$('input.SSNTB').focus();
}, 0);
validToSave = false;
return;
}
$('div.SSNHelp label.Help').html('');
validToSave = true;
});
Works for me. : ]
You have to use regex. Regex is of help in these kind of situations.
Learn more about it from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp

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