表格输入检查Javascript

时间:2015-03-01 08:50:35

标签: javascript forms

我有一个html表单,想要创建一个可以检查电话的Javascript代码。字段仅包含数字。这是一个练习,所以我不想使用jQuery或任何其他库。我把它放在一起:

HTML

<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1" onsubmit="return numberedFieldsCheck()">
<table>
<tr>
<td>
 <label for="tel">Telephone</label></td>
<td>
 <input type="text" placeholder="00441293603275" name="tel" id="tel" />
 <span id="telFieldIntCheck" style="display:none;color:red">You can only use numbers.</span>
</td>
<td>
 <input type="submit" name="button" id="button" value="Submit" />
 </td>
</tr>
</table></form>

JS

function numberedFieldsCheck(){
    var x=document.getElementById('tel').value;// retrieving value from the form
    console.log(x);
    if(!integerCheck(x)){
        alert('wrong format');
        document.getElementById('telFieldIntCheck').style.display="inline";
        return false;
        }
    }

function integerCheck(userInput) {
var userInputArr=userInput.split('');
for (i=0;i<userInputArr.length;i++){
    if (typeof userInputArr[i]=="number")
            {console.log('format ok')} 
    else {return false};
  }
}

你能帮我解决一下代码吗?无论我输入到输入字段中,它都会发出错误的格式警报。控制台日志显示一毫秒并立即消失。

1 个答案:

答案 0 :(得分:1)

由于您只需要检查该字段是否仅包含数字,这应该有效:

function numberedFieldsCheck(){
    var x=document.getElementById('tel').value;

    // Checks if the field is empty.
    if(x.trim() == '') {
    alert("Tel field can't be empty.");
    return false;
    }

    if(!integerCheck(x)){
        alert('Wrong format !');
        document.getElementById('telFieldIntCheck').style.display="inline";
        return false;
    }

    alert("Alright !");
    // Note that this return true is important. You weren't 
    // returning anything even in the case where everything was fine. 
    // If you don't, it will return 'undefined' by default, which is 
    // casted to 'false' in checks. So that means the function returns
    // false even if everything is alright.
    return true;
}

function integerCheck(userInput) {

    // Now, all the elements of usrInputArr will contain strings only.
    // That means typeof <element> will always return "string".
    var userInputArr=userInput.split('');

    for (i=0;i<userInputArr.length;i++){
        char = userInputArr[i];
        // Comparing by ASCIIs should work just fine.
        if (! (char >= '0' && char <= '9' || char == ' ') )
            return false;
    }

    return true;
}

您还应该在问题的评论中执行@hindmost所说的内容,即将表单onsubmit更改为return numberFieldCheck()