如何使用javascript验证html中的文本字段

How would i validate a text field in html using javascript?

本文关键字:文本 字段 html 何使用 javascript 验证      更新时间:2023-09-26

我有一个文本字段供用户输入,检查编号为4位数。如何验证文本字段以确保输入的数字正好是4位(包括前导0)。

到目前为止,我已经验证了它,所以它不会被留空。这是我的Javascript:

function validateForm() 
{
    var result = true;
    var msg="";
    if (document.ExamEntry.name.value=="")
    {
        msg+="You must enter your name 'n";
        document.ExamEntry.name.focus();
        document.getElementById('name').style.color="red";
        result = false;
    }
    if (document.ExamEntry.subject.value=="")
    {
        msg+="You must enter the subject 'n";
        document.ExamEntry.subject.focus();
        document.getElementById('subject').style.color="red";
        result = false;
    }

    if (document.ExamEntry.ExamNo.value=="")
    {
        msg+="You must enter your Examination number 'n";
        document.ExamEntry.ExamNo.focus();
        document.getElementById('ExamNo').style.color="red";
        result = false;
    }

    if(msg=="")
    {
        return result;
    }
    {
    alert(msg)
    return result;
    }
}

这是我的html:

<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
    <table width="50%" border="0">
        <tr>
        </tr>
        <tr>
            <td id="name">Name</td>
            <td><input type="text" name="name" /></td>
        </tr>
        <tr>
            <td id="subject">Subject</td>
            <td><input type="text" name="subject"/></td>
        </tr>
        <tr>
            <td id="ExamNo">Examination number</td>
            <td><input type="text" name="ExamNo"/></td>
        </tr>

        <tr>
            <td><input type="submit" name="Submit" value="Submit" onClick="return validateForm();" /></td>
            <td><input type="reset" name="Reset" value="Reset" /></td>
        </tr>
    </table>
</form>

/^'d'd'd'd$/.test(document.ExamEntry.ExamNo.value)

它返回一个布尔值,用于检查ExamNo是否与该正则表达式(4位字符串)匹配。

完整示例:

if (!/^'d'd'd'd$/.test(document.ExamEntry.ExamNo.value))
    {
        msg+="Examination number should be 4-digit number. 'n";
        document.ExamEntry.ExamNo.focus();
        document.getElementById('ExamNo').style.color="red";
        result = false;
    }

请参阅以下链接

http://jqueryvalidation.org/documentation/

http://jqueryvalidation.org/files/demo/

这是一个验证插件,易于使用。