I wish I could solve this by myself, but I have never quite grasped regular expressions. They seem so powerful. I wanted to ask where is the best resource to learn javascript reg ex, but that was to subjective and I didn't want my question closed. I have a textbox on a web form, when it has a value, that value should be an integer between 1 & 999999. I already use the jquery numeric plug in to only allow digits, all other keystrokes are rejected, there is an onBlur implementation, that if some regex is not matched, a callback will be called... This is that code...
$.fn.numeric.blur = function()
{
var decimal = $.data(this, "numeric.decimal");
var callback = $.data(this, "numeric.callback");
var val = $(this).val();
if(val != "")
{
var re = new RegExp("^\\d+$|\\d*" + decimal + "\\d+");
if(!re.exec(val))
{
callback.apply(this);
}
}
}
Can I modify that regex to assure the val is a valid integer between 1 and 999999? Any help would be appreciated. Also obviously I would like to do this by myself, whats an easy way to learn javascript regex? Thank you all so much. Have a terrific holiday all!
Cheers,
~ck in San Diego
In this particular case, I would recommend not to use a regular expression. Just use plain good old Javascript:
if( typeof decimal === 'number' && (decimal > 1 && decimal < 999999) ) {
// here we go
}
To cast a value into a number, you can either use the +
operator or .parseInt()
var val = +$.trim($(this).val());
if( val && (decimal >= 1 && decimal <= 999999) ) {
}
This would do the job:
[0-9]{1,6}
I would suggest using an integer parsing/validation function instead though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With