我正在尝试通过JavaScript验证HTML文档中的Firstname和Surname字段。验证必须提示用户是否插入了有效的名称/姓氏,这意味着输入框中不应包含任何数字或奇怪的字符。
我一直在寻找stackoverflow和其他类似网站的解决方案但不幸的是我找不到我想要的确切解决方案所以我希望这个网站周围的人可以伸出援助之手。
这是我的HTML代码:
<form name="contact" method="post" action="contact.php">
<table width="200" border="0" align="center">
<tr>
<td><p class="pagetext">Name:</p></td>
<td><input type="text" name="fname" id="fname" size="30"/></td>
</tr>
<tr>
<td><p class="pagetext">Surname:</p></td>
<td><input type="text" name="sname" id="sname" size="30"/></td>
</tr>
<tr>
<td><p class="pagetext">Email:</p></td>
<td><input type="text" name="email" id="email" size="30"/></td>
</tr>
<tr>
<td><input class="btns" type="submit" onclick="validationMain();validationContact();validationErrors();" value="Submit"/></td>
<td><input class="btns" type="submit" onclick="validationReset()" value="Reset"/></td>
</tr>
</table>
</form>
这是JavaScript代码(省略了不相关的部分,以免混淆问题):
var errors = "";
var textOnly = /^[A-Za-z]+$/;
function validationMain(){
var firstname = document.getElementById('fname');
var surname = document.getElementById('sname');
var email = document.getElementById('email');
//emailRegEx expression from www.regular-expressions.info/email.html
var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (firstname.value == "") {
errors += "First Name Cannot Be Left Empty\r\n";
} else {
if (firstname.value != textOnly.value){
errors += "First Name is Invalid\r\n";
}
}
if (surname.value == "") {
errors += "Surname Cannot Be Left Empty\r\n";
} else {
if (surname.value != textOnly.value){
errors += "Surname is Invalid\r\n";
}
}
if (email.value != ""){
if (email.value.search(emailRegEx) == -1){
errors += "Invalid Email Entered\r\n";
}
} else {
errors += "Email Cannot Be Left Empty\r\n";
}
}
主要问题是我在文本字段中输入的名称或姓氏(即使它们是正确的没有数字和特殊字符)它会提示它们无效(不应该是这种情况)所以我'我猜我的if条件有问题。
提前感谢您的时间,帮助以及提供的任何相关信息:)
我希望我提供足够的信息,如果没有,请告诉我!
答案 0 :(得分:2)
你没有正确使用你的表达。
textOnly.test(firstname.value);
test
检查表达式是否匹配。
答案 1 :(得分:0)
以下行将文本字段中的值与正则表达式的属性值进行比较。
if (firstname.value != textOnly.value){
您需要使用regexp测试该值,看它是否有效。