Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form validation numeric range (minimum/maximum) in JavaScript

Have a script that defines text as being a number using a regular expression:

function validateTextNumericInRange(textInputId)
{
    var numRegex = /^[\d]+$/;
    var textInput = document.getElementById(textInputId);

    var valid = true;
    if (numRegex.test(textInput.value) == false) {
        alert('Value must be a number between 3-48');
        valid = false;
    }
    return valid;
}

Need to use this format and provide a min/max range (arbitrary for now, say between 3 and 48). How would I modify this regex to complete and have a correct argument?

like image 804
Robert Avatar asked Apr 27 '11 19:04

Robert


2 Answers

I don't understand your question. Do you mean that you want a number that is between 3 and 48 digits, or that the value of the number must be between 3 and 48?

For the latter you don't need a regex:

function validateTextNumericInRange (textInputId) {
    var textInput = document.getElementById(textInputId);
    var value = parseInt(textInput.value, 10);

    return (!isNaN(value) && value >= 3 && value <= 48);
}

A more generic solution:

function validateTextNumericInRange(textInputId, min, max) {
    var textInput = document.getElementById(textInputId);
    var value = parseInt(textInput.value, 10);

    return (!isNaN(value) && value >= min && value <= max);
}

To test to see if a number is between 3 and 48 digits long, you can use the regular expression /^[0-9]{3, 48}$/.

like image 51
Vivin Paliath Avatar answered Nov 06 '22 04:11

Vivin Paliath


A regular expression would be hard and inflexible, and for your example it would be:

/^(?:[3-9]|[1-3][0-9]|4[0-8])$/

Better go with Vivins' solution.

like image 25
stema Avatar answered Nov 06 '22 04:11

stema