简体   繁体   中英

regex in javascript - variable inside regex

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--
    }
}

请参考RegExp类(http://www.regular-expressions.info/javascript.html)

var regex = new RegExp("^\d{1,"+min_length[i] + ",}$"); 

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM