0

Basically i want to return an error if the value of a field is non-numeric or less than a defined minimum length (from array). i'm struggling to get this javascript to work:

var fields = new Array("field_1","field_2","field_3");
var length = new Array(12,4,3);
for (i=0; i < fields.length; i++) {
    var regex = "/^[\d]{" + min_length[i] + "}$/";   //
var field = document.getElementById(numeric_fields[i]);
if (!regex.test(field.value)) {
        alert("error");
    }
    else {
        --do other stuff--
    }
}

2 Answers 2

2

Please refer to RegExp class(http://www.regular-expressions.info/javascript.html):

var regex = new RegExp("^\d{1,"+min_length[i] + ",}$"); 
Sign up to request clarification or add additional context in comments.

4 Comments

hmm.. var regex = new RegExp("/^[\d]{" + min_length[i] + "}$/"); doesn't seem to work?
{n} means exactly n matches, so to validate less than a specific length should use {n,}, pay attention to the comma.
Sorry, it should be {n,m} m means max length
You need to remove the slashes. Use regex.toString() to check the result.
1

Regular expressions can be handy for a lot of things, but for simpler tasks they are not the most efficient way. How about determining if the field is not a number and is of a certain length:

var fields = ["field_1", "field_2", "field_3"];
var length = [12, 4, 3];
for (var i = 0, len = fields.length; i < len; i++) {
    var field = document.getElementById(numeric_fields[i]);
    var value = field.value;
    if (isNaN(field.value) || field.value.toString().length < min_length[i]) {
        alert("error");
    } else {
        // do other stuff
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.