這裏的問題是名字和姓氏進行驗證在一起請清理,當我點擊名字textfield驗證應檢查名字只不是姓氏........ .................................................. .................................................. 。jquery keypress,keyup和keydown實時驗證
<html>
<head>
<title>s1</title>
<style type="text/css">
body {font-family:"Trebuchet MS",verdana;width:800px;}
#info {color:#008000;font-weight:bold; }
#age {width: 40px;}
.error_msg { color: red;}
#content{ color: red; }
span.error {font-size: 11px; color: #D8000C; }
.emsg{ color: red; }
.hidden { visibility:hidden;}
</style>
</head>
<body>
<form method="post" id="forms1">
<fieldset>
<legend><strong>Please fill the information</strong></legend>
<table>
<tbody>
<tr>
<td>First Name:</td>
<td><input type="text" id="fname" class="required name" />
<span class="emsg hidden">Please Enter a Valid Name</span>
</td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" id="lname" class="required name" />
<span class="emsg hidden">Please Enter a Valid Name</span>
</td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" id="age" maxlength="3" class="required age" />
</tr>
<tr>
<td>Address:</td>
<td><input type="text" id="address"/> </td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Save" id="save" /></td>
</tr>
</tbody>
</table>
</fieldset>
</form>
<p id="content"></p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
var $regexname=/^[A-z]+$/;
$('.name').on('keypress keydown keyup',function()
{
if (!$(this).val().match($regexname))
{
// there is a mismatch, hence show the error message
$('.emsg').removeClass('hidden');
$('.emsg').show();
}
else
{
// else, do not display message
$('.emsg').addClass('hidden');
}
});
});
</script>
</body>
</html>
becoz您正在使用類名來驗證函數和兩個元素具有相同的類 –