Reputation: 29
I am a newbie to javascript. I need serious help with a form validation using javascript. Here is what i need the script to perform.
When a user fills a form and he enters numbers other than multiples of 20,(Like 40,60,80,100) he should get an alert.
Example: If i enter 45 on an input field, i should get an error like "You have entered an invalid amount."
{else}
Post form.
Upvotes: 1
Views: 1249
Reputation: 11504
@Kooilnc is correct, but here's a more complete solution: http://jsfiddle.net/nottrobin/vN3xK/
<form name="numberForm">
<input type="number" name="number" />
<button type="submit">submit</button>
</form>
<script>
// NB: jQuery is required
jQuery('[name="numberForm"]').bind(
'submit',
function(evt) {
if(jQuery('[name="number"]').val() % 20 != 0) {
alert('Your number is wrong');
evt.preventDefault();
}
}
);
</script>
Can I suggest you use %
instead of regex, 'cos it's way much neater.
Upvotes: 0
Reputation: 699
In jQuery
if($('#input_id').val() % 20 != 0)
{
$('#input_id').val('');
alert('You have entered an invalid amount.');
}
else
{
//success
}
Upvotes: 0
Reputation: 122888
Try using the %
(modulus) operator
if ((+([value of inputfield])||1)%20 === 0) { /* is multiple of 20 */ }
// ^convert to Number ^
// ^if conversion fails, use 1 for value
// (so %-operation will not fail)
See this jsfiddle for a simple example
Upvotes: 2