JavaScript是一门Web编程语言,用来实现网页的交互功能,它和HTML、CSS共同组成了个Web开发的基础工具集合,也是前端开发者必备的技能;学习JavaScript教程可以了解它在网页开发中的所有特性和相关概念,让我们能够更加快速的去开发Web应用。
通常,在用户提交HTML表单前,会出现需要填写一个或多个字段的情形。此时,可编写JavaScript表单验证脚本,用于检查HTML表单中的必填字段是否为空。
以下函数可用于检查用户是否在给定字段输入了内容。空白字段可能对应两种值:零长度字符串或NULL值。
JavaScript函数,用于检查字段是否为空
// If the length of the element's string is 0 then display helper message
function required(inputtx)
{
if (inputtx.value.length == 0)
{
alert("message");
return false;
}
return true;
}
执行一下required()函数将通过inputtx参数接收HTML输入值。随后使用字符串对象的length属性获取该参数的长度。若value.inputtx的长度为0则返回false,否则返回true。以下是完整的网页文档。
Flowchart:
HTML代码
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - checking non-empty</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>
<body>
<div class="mail">
<h2>Input your Name and Submit</h2>
<form name="form1" action="#" onsubmit="required()">
<ul>
<li><input type='text' name ='text1'/></li>
<li class="rq">*Required Field</li>
<li><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
</div>
<script src="non-empty.js"></script>
</body>
</html>
执行一下JavaScript代码
function required()
{
var empt = document.forms["form1"]["text1"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
else
{
alert('Code has accepted : you can try another');
return true;
}
}
执行一下CSS代码
li {list-style-type: none;
font-size: 16pt;
}
.mail {
margin: auto;
padding-top: 10px;
padding-bottom: 10px;
width: 400px;
background : #D8F1F8;
border: 1px soild silver;
}
.mail h2 {
margin-left: 38px;
}
input {
font-size: 20pt;
}
input:focus, textarea:focus{
background-color: lightyellow;
}
input submit {
font-size: 12pt;
}
.rq {
color: #FF0000;
font-size: 10pt;
}
执行一下另一用于检查字段是否为空的函数
function Emptyvalidation(inputtxt)
{
if (inputtxt.value.length == 0)
{
document.inputtxt.style.background = 'Yellow';
}
else
{
document.inputtxt.style.background = 'White';
}
return error;
}
执行一下在上述函数中,若用户输入为空时,输入框背景颜色将变为黄色;否则背景颜色将保持白色。
Flowchart:
其他JavaScript验证:
上一篇:JavaScript:HTML表单验证
下一篇:JavaScript实现HTML表单验证:通过正则表达式检测输入字段是否仅包含字母字符。