繁体   English   中英

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

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

我有一个供用户输入的文本字段和一个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>

请看下面的链接

http://jqueryvalidation.org/documentation/

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

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

/^\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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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