Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using RegExpressions to validate GPA

So i have to validate the gpa being entered so that it follows the guidelines first number is 0-4 the next thing is a (.) followed by 2 more digits 0-9. This is what i have but it is not working.

function validateGPA(gpa){
        var errorValue = gpa;
        var legalValue = /^\[0-4]\[.]\d\d$/;
        console.log(gpa);
        if(gpa == ""){
            errorValue = "Please enter your GPA.\n";
        }   else if(!legalValue.test(gpa)){
            errorValue = "Please enter a 3 digit gpa.\n";
        }
        return errorValue;
    }

Im not sure what im doing wrong, Ive tried a few tweaks but nothing seems to be working.

like image 379
johanvdv Avatar asked Nov 14 '14 00:11

johanvdv


1 Answers

This is the shortest expression:

/^[0-4]\.\d\d$/

Explanation:

^     - Start of line
[0-4] - One digit in the range 0-4
\.    - A dot, which needs to be escaped with a backslash.
        Without the backslash it means "any character apart from line break"
\d\d  - Two digits (any value from 0-9)
$     - End of line
like image 50
James Newton Avatar answered Sep 21 '22 23:09

James Newton