0

I'm trying to get it so that the alert message pops up if the value entered into the textBox is not a decimal number between 0.0 and 4.9 with just one digit before and after the decimal, but the message pops up regardless of what number I entered and I think there's something wrong with my regular expression but I can't figure it out.

if ((textBox.value.search("/^[0-4]\\.[0-9]$/")) == -1) {
    alert("Invalid Entry");
    return false;
}

The return false is there since if the number is invalid then the function will exit.

2 Answers 2

1

You could also do this without using a RegExp, by parsing the value to number via parseFloat and checking the result via isFinite.

// Parse the value as a float. If the value cannot be parsed,
// `parseFloat` will return NaN    
var toFloat = parseFloat( textBox.value );

// Use `isFinite` to verify that parsing was successful. If it
// was, just check the range (i.e. between 0 and 4.9)
if ( isFinite( toFloat ) && toFloat >= 0 && toFloat <= 4.9 ) {
    // Input is valid
} else {
    // Input is invalid
}

hope that helps. cheers!

Sign up to request clarification or add additional context in comments.

Comments

0

It should be:

if ((textBox.value.match(/^[0-4]\.[0-9]$/))) {
    alert("Invalid Entry");
    return false;
}

Here you aren't interested in the position of match but only in the fact of matching so it isn't necessary to use search, match is enough.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.