验证变量javascript

时间:2014-08-18 21:33:33

标签: javascript validation

我需要使用javascript验证一些用户输入。我需要检查他们的条目(值)是否是正确的类型(类型)。

我需要我的正则表达式模式以确保值只包含数字而不包含任何其他值,除了测量类型也可以包含小数点。

这样做的正确方法是什么?我的方式似乎可能是,但我猜。在任何情况下,我的正则表达式模式都有问题,因为它抛出了代码注释中声明的错误。

这是我的代码:

    function validateInput(value, type) {
console.log(value);
if(type === "Integer"){
    var patt = new RegExp("^\D", i);
}
else if(type === "Measurement"){
    var patt = new RegExp("^\D", i); //Uncaught SyntaxError: Invalid flags supplied to RegExp constructor '2' 
}
else{
    return true;
}


if(patt.test(value)){
    return false;
}
else{
    return true;
}
}




function sendObs() {
    RID = $("#oid").val();
    console.log(RID);
    var children = $("#abc").children();
    var xmlString = "<root><rid>" + RID + "</rid>";

    for(i=0; i < children.length; i++){
        var value = children[i].children[0].value;
        var type = children[i].children[0].id;
        var validationResult = validateInput(value, type);
        if(!validationResult){                //calling the validation method here
            alert("invalid entry");
            return;
        }
        var code = children[i].children[0].className;
        xmlString += '<question><code>' + code + '</code><value>' + value + '</value></question>'
    }
    xmlString +='</root>'
    console.log(xmlString);
    data = $.parseXML(xmlString);
    console.log(data);

    //send it here

}

1 个答案:

答案 0 :(得分:0)

您可以拨打parseInt()parseFloat()

,而不是使用正则表达式

除了将字符串转换为可行数字之外,如果输入无效,则两个函数都会返回NaN

number = parseFloat(string)

if (isNaN(number)) {
    # `string` is invalid 
}