输入数据验证过程出错

时间:2011-07-19 10:04:43

标签: javascript jquery

目标:
如果输入数据包含任何字母,我不想检索任何数据。

问题:
如果我在变量ddd中输入数据“23w”,则转换过程在变量currentvalue中可以被认为是“23”。

  

如果输入数据包含,我不希望它被转换为数字   任何字母。

源代码在jQuery中写入,如果可能的话,在jQuery中检索新的解决方案会很棒。

// Fullmetalboy


    var ddd = $('#field_hourInput').val();

    var currentValue = parseInt(ddd);


    // Validating message
    if(currentValue <= 0)
    {
        alert("Value must be positiv");
        nonError = false;
    }
    else if(  (isNaN(currentValue)) && (ddd != "")  )
    {
        alert("value must contain numbers");
        nonError = false;
    }
    else if(  (isNaN(currentValue)) &&  (ddd == "")  )
    {
        alert("value must contain value in the textbox");
        nonError = false;
    }   

3 个答案:

答案 0 :(得分:0)

您可以使用正则表达式来验证它。 Using regex with jquery。并使用正则表达式

  

[\ d]

将匹配任何数字应该可以解决问题。

答案 1 :(得分:0)

将字符串转换为int的另一种方法是Number(ddd),它可以满足您的期望。但你也可以通过正则表达式查看ddd,这对我来说感觉更好。

regexp-test:/ ^ \ d + $ / .test(ddd)

答案 2 :(得分:0)

如果字符串以1开头,

parseint()将返回一个数字,即使其后面有非数字也是如此。例如:http://jsfiddle.net/uQztw/

使用正则表达式可能更好。像

这样的东西

http://jsfiddle.net/uQztw/1/