Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a textbox to check if the value entered is in multiples of 100 only

I want to validate that the value entered by a user in a textbox is a multiple of 100 using jQuery. How can I do that?

like image 670
TJ- Avatar asked Jan 21 '26 01:01

TJ-


2 Answers

This will check whether the value of the element matching #example is a multiple of 100 and store the result (true or false) in multiple:

$("#example").change(function() {
   var multiple = parseInt($(this).val(), 10) % 100 == 0; 
});

Note that this will result in 0 returning true, so you may want to add a check in for that.

Here's a live example. See MDN article for more information on the modulus operator.

Update (based on comments)

As noted by @PaulPRO in the comments, the above will also return true for numbers such as 100.973. If you want to deal with floating point numbers as well as integers, simply use parseFloat instead of parseInt. Here's another live example, and here's some updated code:

$("#example").change(function() {
   var multiple = parseFloat($(this).val()) % 100 == 0; 
});
like image 77
James Allardice Avatar answered Jan 23 '26 14:01

James Allardice


There are a lot of fun ways. Lets collect the input value itself:

var input = $('#textbox').val();

So, ways:

  1. The boring right way

    if (parseInt(input,10) % 100 === 0)
    
  2. A bit more fun way

    if (input.substr(-2)==='00')
    
  3. "I love odd bases"

    if (parseInt(value,13) % parseInt('79',13) === 0)
    
  4. Regexes

    if (input.match(/[1-9]+00$/))
    
  5. More fun (but definitely more robust) regexes

    if (input.match(/\s*\d+0{2}\s*$/))
    
  6. And the winner is...

    if ((input.search(/\s*\d+0{2}\s*$/)==-1?"false":"true" !== "false"))
    

But if I were you I'd stop with first way. :)

like image 34
J0HN Avatar answered Jan 23 '26 14:01

J0HN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!