JoseBazBaz
JoseBazBaz

Reputation: 1445

Form Validaton Code Not Working

var val_regex = \d{3}+(\.[0-9]{1,2})?$
function validate(form){
    var valOne = form.valone.value;
    var valTwo = form.valtwo.value;
    var valThree = form.valthree.value;


     if (!val_regex.test(valOne)) || (!val_regex.test(valTwo)) ||(!val_regex.test(valThree)){
        $("#val-error").html("Error with inputted value");
        $('#val-error').fadeIn(200).delay(1500).fadeOut(800);
        return false;
     }
     return true;
    }
}

My regex expression here doesn't seem to be working. Can you see what the problem is?

Regex expression - what I want - any number between 0 and 999 (inclusive) - there is a maximum of 2 decimal places allowed. Am I writing the regex expression the wrong way or is my javascript wrong?

Upvotes: 1

Views: 71

Answers (2)

Meower68
Meower68

Reputation: 1009

var val_regex = /^\d{1,3}(\.\d{1,2})?$/;

Explanation:

\d{1,3}

Allow 1-3 digits.

\d{1,3}(\.\d{1,2})?

Allow 1-3 digits and, optionally, allow a period and 1-2 more digits.

^\d{1,3}(\.\d{1,2})?$

All of the above, but allow nothing else before or after it. Make sure you .trim() your inputs to eliminate any whitespace before and after.

This will allow "0" - "999". It will also allow "0.0", "0.00" and "999.99" but not "0." (must have at least digit after the decimal place).

Upvotes: 0

Will C.
Will C.

Reputation: 599

Your regular expression doesn't match single, or double digit numbers.

Try this:

var val_regex = /^(([0-9])|([1-9][0-9])|([1-9][0-9][0-9]))(\.[0-9]{1,2})?$/;

Upvotes: 1

Related Questions