Welcome to WebmasterWorld Guest from 50.16.78.128

Forum Moderators: open

Message Too Old, No Replies

Limit Number Values inside HTML Form input field

How to limit number values inside form input field

   
11:04 am on Feb 3, 2014 (gmt 0)

5+ Year Member



Hi,

I have following form:

<form action="action/balancePayPal.php" method="post">
<input class="span2" value="20" name="accBalance" />
<button class="btn btn-large btn-payment" name="balanceSubmit" value="Submit">Submit &raquo;</button></p>
</form>


and I want to block users to submit the form if the value/amount they enter is lower then 20 and larger then 10000, and also don't allow them to enter anything else beside numbers inside that input field.

How do I achieve that with JQuery.

Thanks for help!
3:14 pm on Feb 3, 2014 (gmt 0)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



Are decimal values allowed? 20.1, etc.?
5:46 pm on Feb 4, 2014 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



Note: If your answer to Fotiman's question is "no", use this regular expression instead of the one below:
/^\d+$/

First, attach an id or a class to your form. In this example I'm assuming an id of number_form
$('#number_form').on('submit', function(event) {
var accBalance = $(this).find('[name="accBalance"]:first').val();

if(!accBalance.match(/^\d+(\.\d+)?$/)) {
alert('Account balance must be numeric');
event.preventDefault();
return false;
}

accBalance = parseFloat(accBalance);
if(accBalance < 20 || accBalance > 10000) {
alert('Account balance must be between 20 and 10,000');
event.preventDefault();
return false;
}

return true;
});

NB: Do not rely on this validation for your server side code. All javascript validation can be very easily circumvented.