Javascript validation on Floating values - javascript

How to do decimal validation using javascript?
There is a text box which should accept only 24.00 or 24 or any value less than 24.00.
The text box also must allow if 23.99 is entered.
I tried it this way:
if (document.forms[0].hours!= undefined) {
var val = document.forms[0].hours.value;
if (val .match(/^\d{0,6}(?:\.\d{0,2})?$/)) {
alert("Invalid" +'${payType}'+" Hours. The hours entered can not have more than 2 decimal places or should be in the range of 0 to 24 ");
submitted=false;
return false;
}
}
The values can be: 1.00 or 12.25 or 1.25 or 23.99 or 24 but not above these values. Any number below 24.00 or 24.

If you prefer doing it with regex try this
^(0+)?(24(\.00?)?|(\.00?)?|\.[0-9]+|0?[0-9](\.[0-9]{0,2})?|(0+)?[0-2][0-3](\.[0-9][0-9]?)?)$
Tested on all the values below
0.0
4.00
4.01
024.0
5.8
2.95
10.5
10.00
023.9
011
09.89
09
8.67
24
24.00
24.0
23.99
0.00
0
.5
.55
6
24.01 // fail
13.90
78.23 // fail
1.56
0.06
25.00 // fail
23.99
41.00 // fail
Demo
The section below isn't related to the answer but rather to the comments below. #Anto these are just a few of online resources on regex. Have fun ;)
Free online books (google for these books)
Mastering Regular Expressions, 3rdEdition
Introducing Regular Expressions
Regular Expression Pocket Reference, 2nd Edition
Regular Expressions Cookbook
Good websites
http://www.regular-expressions.info
http://www.rexegg.com
http://regexlib.com
http://overapi.com/regex/
Online regex tester
http://regex101.com/

You could try the below regex,
^(?:24\.00|24|(?:[0][1-9]|[1][0-9]|2[0-3])\.[0-9][0-9])$
DEMO
OR
If you don't want 0 before the digit then you could try the below
^(?:24\.00|24|(?:[1-9]|[1][0-9]|2[0-3])\.[0-9][0-9])$
DEMO

you can reverse thinking
allow any number above 24.00 or 24
var reg = /^(24\.(0[1-9]|[1-9]\d?)|([3-9]\d|[^0]\d{2,9}|2[5-9])(\.\d{1,2})?)$/
3.33 fail
23.00 ...
24 ...
24.00 ...
0.00 ...
0 ...
24.01 pass
34.01 ...
34 ...
120.18 ...
if (document.forms[0].hours!= undefined) {
var val = document.forms[0].hours.value;
if (!reg.test(val)) {
alert("Invalid" +'${payType}'+" Hours. The hours entered can not have more than 2 decimal places or should be in the range of 0 to 24 ");
submitted=false;
return false;
}
}

You don't need regular expression for this at all.
In fact it would be a lot simpler to just do this:
if (document.forms[0].hours!= undefined) {
var val = parseFloat(document.forms[0].hours.value);
// Get the number of decimals
var a = val.toString().split(".");
var decimals = a.length > 1 ? a[1].length : 0;
if (isNaN(val) || val < 0 || val > 24 || decimals > 2) {
alert("Invalid" +'${payType}'+" Hours. The hours entered can not have more than 2 decimal places or should be in the range of 0 to 24 ");
submitted=false;
return false;
}
}

Related

Regex to match numbers between 0 to 25 both inclusive which can be doubles with 1 precision

I want to use Regex to match numbers between 0 to 25 both inclusive which can be doubles with 1 precision.
For ex.- 2, 2.5, 23.0, 8, 24.3, 25
I created following regex-
^(\\s*|0?[0-9]|[0-9]|1[0-9]|2[0-5])$
But it works only for numbers between 0 to 25 both inclusive.
This is the regex pattern I would use here:
^(?:(?:[0-9]|1[0-9]|2[0-4])(?:\.[0-9])?|25(?:\.0)?)$
Demo
The pattern is similar to what you used, except that we only match 2[0-4] with any single decimal point. The end point 25 is a special case, which can only take 25.0 at most for its decimal component.
But in general it would easier in JavaScript to just parse the text number, and then use an inequality to check the range. E.g.
var number = '24.3'
if (number >= 0 && number <= 25.0) {
console.log('within range');
}
To verify the validity, use the >= and <= operators. To meet the regex requirement, just add a garbage regex expression.
let isMatch = number => {
'must use regex'.match(/x/);
return number >= 0 && number <= 25;
};

How does ~5 return -6?

I am asking this question as a follow up to my previous question.
The page at W3chools says:
The examples above uses 4 bits unsigned binary numbers. Because of this ~ 5 returns 10.
Since JavaScript uses 32 bits signed integers, it will not return 10.
It will return -6. 00000000000000000000000000000101 (5)
11111111111111111111111111111010 (~5 = -6)
A signed integer uses the leftmost bit as the minus sign.
Inverting the bits and chopping off the sign bit, the number becomes 1111111111111111111111111111010, which evaluates to 2147483642 in decimal form. According to the page, however, it should evaluate to -6.
Where did I go wrong?
The mistake lies in "chopping off the sign bit" of the 32 bit complemented result. This converts -6 (which has lots of leading 1s in it's binary representation) into a 31 bit positive number which still has lots of leading 1s in its binary representation. The 31 bit number obtained by removing the sign bit from -6 is very close to the maximum positive value of a 32 bit signed number.
You can see the results without removing the 32 bit integer sign bit:
function unsignedNibble( i) {
return i & 0x0f;
}
function signedNumberBits( n) {
var bits = "";
for( var i = 32; i--;) {
bits = "" + (n&1) + bits;
n = n >> 1;
}
return bits;
}
console.log("Unsigned 4 bit: ");
var un5 = unsignedNibble( 5); // unsigned 4 bits of 5
console.log( "un5 = %s ( 0b%s)", un5, un5.toString(2));
var notUn5 = unsignedNibble( ~un5);
console.log( "~un5 = %s ( 0b%s)", notUn5, notUn5.toString(2));
console.log("Signed 32 bit: ");
var sn5 = 5; // signed number 5
console.log( "sn5 = %s ( 0b%s)", sn5, sn5.toString(2));
var notSn5 = ~sn5;
console.log( "~sn5 = %s ( 0b%s)", notSn5, signedNumberBits(notSn5));
#wais
6 is represent as 0000 0110 (0 has been padded)
now to get -6 we have to make 2's Complement for that
Step 1 - Reverse all the bits (1st Complement)
1111 1001
Step 2 - Add 1 (0000 0001)
1111 1001 + 0000 0001 = 1111 1010
In 2's compliment, you add 1 at the end after the bits are all complimented to get the negative number's absolute value.
1111111111111111111111111111010 is complimented to get ...0101 (which is 5), but then you add 1 to get 6. Remembering this was a negative number you're determining, you slap the negative sign on to get -6.
JavaScript binary numbers are stored in two's complement format.
This means that a negative number is the bitwise NOT of the number plus 1. For example:
Binary Representation Decimal value
00000000000000000000000000000101 5
11111111111111111111111111111011 -5
00000000000000000000000000000110 6
11111111111111111111111111111010 -6
00000000000000000000000000101000 40
11111111111111111111111111011000 -40
Source: https://www.w3schools.com/js/js_bitwise.asp
~ operator just do bit change.
such as ~5 = ~(00000101) it returns (11111010) = -6
Don't make ~ operator too complicated.

JQuery validate regular expression to get interest rate

I want regular expression to get rate of interest. I am wanting to accept following things:
Ex:
0
0.4
0.44
4
44
4.00
44.00
4.2
4.22
44.22
Min 0 and Max 99.99
It must have to accept numeric as well as decimal values but not more than 99.99. Also it should take decimal after first or second digit and after third digit it should display an error message.
I am trying this regular expression but its not perfectly working for me.
$.validator.addMethod('interest', function(value, element) {
return this.optional(element) || /\d{1,2}\.?\d{0,4}/.test(value);
}, 'Please specify a valid data');
Any help would be appreciated.
A regex to match all of those numbers between 0 and 99.99 would be:
^\d{1,2}(\.\d{1,2})?$
so you're pretty close, but your regex matches 0 to 4 digits after the .
EDIT: forgot ^$
Why mess with regexes if you can simply check for the value:
var input = parseFloat(value)
return !isNaN(input) && input >= 0 && input < 100;
If you want to make sure there are at most 2 decimal placed in the string, the check will be a little longer:
return !isNaN(input) &&
input >= 0 &&
input < 100 &&
!(value.split('.')[1] && value.split('.')[1].length > 2);
If you use regex you will end up having two problems. Try:
function validateStuff(input) {
return ($.isNumeric(input) && input >= 0 && input <= 99.99);
}
// Testing:
console.log(validateStuff(5));
console.log(validateStuff("Hello"));
console.log(validateStuff(100));
console.log(validateStuff(99.99));
DEMO

Need a Regular Expression for the validation of Time format

I have a datetime textbox which contains both date and time .
I want to validate the time.For the date i have validated.
e.g datetime value is 04/23/2013 05:26 pm;
I need a regex which can validate the time that will be in format 00:00:00 .
all are digits and no special character or other than digits will be entered.
i want only to validate dd:dd:dd all are 2 digits.
I can enter for example 10:10:10 and 01:02.
i have tried with js way like this.i have no knowledge in regex.so i want suggestions.
function ValidateDate()
{
//getting the value from textbox
var dateVal=document.getElementById('txtDateTime').value;
//after one space there is time..as i am using a datepicker and timepicker format
var time=dateVal.split(' ')[1];
var isValidTime=CheckTime(time);
}
function CheckTime(time)
{
var timePart=time.split(":");
var hour = timePart[0];
var minute = timePart[1];
var second = timePart[2];
if((parseInt(hour,10)<0) || (parseInt(hour,10)>59))
{
return false;
}
if((parseInt(minute)>59) || (parseInt(minute)<0))
{
return false;
}
if((parseInt(second)<0) || (parseInt(second)>59))
{
return false;
}
return true;
}
Thanks for your suggestions.
A simple regex of /^([0-1][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9]))?$/g will work.
10:00:00 - OK
01:00:00 - OK
60:00:00 - Fail
30 - Fail
30:00 - Fail
23:59 - OK
24:00 - Fail
23:60:60 - Fail
23:59:59 - OK
Regex autopsy:
^ - This is where the sentence MUST start
([0-1][0-9]|2[0-3])
[0-1][0-9] - The digits 0 to 1 followed by any digit between 0 and 9
| - OR
2[0-3] - The digit 2 followed by any digit between 0 and 3
: - A literal : character
([0-5][0-9]) - The digits from 0 to 5 followed by any digit between 0 and 9
(?::([0-5][0-9]))?
?: - a non capturing group
: - A literal : character
([0-5][0-9]) - The digits from 0 to 5 followed by any digit between 0 and 9
? - means that the previous statement should be there 0 or 1 time (so it doesn't have to be there).
$ - This is where the sentence MUST end
The following regex should work: /^\d{2}:\d{2}(?::\d{2})?$/.

javascript regular expressions

Help me with regular expressions. I need to check the text on the hour and minute. That is the first case, the text can be from 0 to 12. In the second case, the text can be from 1 to 60.
this is my code:
var hourRegEx = /^([0-9]{2})$/; //You can fix this line of code?
$(document).ready(
function(){
$('form.form').submit(function(){
if( $('input.hour').val().match(hourRegEx) ){
return true;
}
return false;
});
});
In my case, the code says that, for example 52, too, the correct answer
I would do this with parseInt and numeric checking:
var hour = parseInt($('input.hour').val(), 10);
if((hour >= 0) && (hour <= 11)){
return true;
}
If what you are inherently doing is comparing numbers you really shouldn't use a regex
I would do this:
var numericRegEx = /^[0-9]+$/;
$(document).ready(
function(){
$('form.form').submit(function(){
var hourVal = $('input.hour').val();
if( hourVal.match(numericRegEx) && parseInt(hourVal) <= 11){
return true;
}
return false;
});
});
This may be overly complicated; if I was doing this I would just use parseInt, but the original code would return false for values such as "11blah" so some regex functionality is still used to check the entire string is an integer.
Why not convert it to integer and use <? Regex is not a substitution for integer arithmetics.
Use: /^([0-9]|10|11|12)$/. It's short enough, and very clear :)
Edit: or, if #Jamiec is right and you're mistaken about the numbers, /^([0-9]|10|11)$/
For minutes, use: /^([0-9]|[1-5][0-9])$/.
Edit 2: ah wait, 1 to 60. Use this:
/^([1-9]|[1-5][0-9]|60)$/
and for hours 1-12, if you need it:
/^([1-9]|10|11|12)$/ or /^([1-9]|1[0-2])$/
The RegEx for testing a number between 0 and 12 would be along the lines of ^([0-9]|1[012])$ and for the minutes: ^[1-9]|[2-5][0-9]$.
I wouldn't recommend it though. Personally, I'd use parseInt to get the value as a number. You can check it's a valid number because parseInt will return NaN if it isn't. Then you can do your range check.
var hourVal = parseInt($('input.hour').val(),10),
minVal = parseInt($('input.minute').val(),10);
if(hourVal && hourVal >=0 and hourVal <= 12){
// hour valid
}
if(minVal && minVal >=1 and minVal <= 60){
// min valid
}
This should handle also cases where the user inputs 00-09:
/^(0?[0-9]|1[0-2])$/
This:
[1-9]|1[0-2] will match the hour ( 1 .. 12 )
[1-9]|[1-5][0-9]|60 will match the minutes ( 1 .. 60 )
if you want to match 0 .. 11 and 0 .. 59 do this
[0-9]|1[0-1] will match the hour ( 0 .. 11 )
[0-9]|[1-5][0-9] will match the minutes ( 0 .. 59 )
if you want to match 00 .. 11 and 00 .. 59 do this
0[0-9]|10|11 will match the hour ( 00 .. 11 )
[0-5][0-9] will match the minutes ( 00 .. 59 )
Using regex is not viable for this case. You should compare integer instead, because '1', '01', '001' are valid too.
i recommand this kind of snippet
val = parseInt($('input.hour').val());
if (val >= 0 && val <= 12)
// is valid ...

Categories

Resources