如何使用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>
/^'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/
这是一个验证插件,易于使用。
相关文章:
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 当设置addFromAutocompleteOnly时,剩余文本将保留在输入字段中
- 使用jquery将输入字段转换为文本
- 如何从查询字符串中的输入字段发回文本
- 表单输入字段随着溢出的文本而增长
- 使用单个文本框向多个字段添加严格搜索
- 使用javascript提交表单并从字段/单选框/复选框/文本区域获取数据
- 使用jQuery的输入字段文本换行
- 向使用jQuery加载DOM后添加的字段添加不受限制的文本输入DatePickers
- 当用户单击按钮(在光标位置)时,在输入字段中添加一个文本字符串
- 如何根据文本长度立即显示和隐藏字段?-JQuery
- 如何使文本、数字和日期html输入字段以一致的方式支持Ctrl+Z(撤消)
- 模拟文本输入字段上的退格键
- 输入字段中的可持续文本
- 未获取文本输入字段的值
- 没有文本安全性的密码字段
- 将禁用的输出字段更改为带前缀的文本
- 为什么 react 将输入[类型=“文本”] 字段设为只读,除非我提供 onChange 回调
- 使用SAPUI5中的“文本”字段显示正确的“日期”
- Kendo,如何将MVVM文本:字段绑定到远程DataSource