[英]Javascript form validation error
<html>
<head>
<title> Form Validation </title>
<style type="text/css">
fieldset { width: 280px; padding: 6px; }
label { float: left; width: 100px; font: 12px Arial; padding: 5px; }
input { margin-bottom: 5px; }
</style>
</head>
<body>
<form id="inputForm" onsubmit="return validateForm();" action="#">
<fieldset>
<label>First Name:</label><input type="text" name="first_name" /><br />
<label>Surname:</label><input type="text" name="surname" /><br />
<label>Postcode:</label><input type="text" name="postcode" /><br />
<label>Email:</label><input type="text" name="email" /><br />
<input type="submit" name="submit" value="Send form" />
<input type="reset" name="reset" value="Reset" />
</fieldset>
</form>
<script type="text/javascript">
function validateForm() {
var form = document.forms['inputForm'];
var formats = {
First_name: /^[a-z]+[\-`\s]?[a-z]+$/i,
Surname: /^[a-z]+[\-`\S]?[a-z]+$/i,
Postcode: /^\d{4}$/,
Email:/^w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/
};
var elCount = form.elements.length;
for(var i = 0; i <elCount; i++) {
var field = form.elements[i];
if(field.type == 'text') {
if(!formats[field.name].test(field.value)) {
alert('Invalid '+field.name.replace('_', ' '));
field.focus();
return false;
}
}
}
}
</script>
</body>
</html>
Hey guys trying to figure out why the code is giving me a error:underfinded formats[fields.Name] but its has been defined. 大家好想弄清楚为什么代码给了我一个错误:格式不足[fields.Name],但是它已经定义了。 Its just a simple form so I am not sure what I am doing wrong.
它只是一种简单的形式,所以我不确定自己在做什么错。 Sorry for the basic question but I have been looking over it multiple time and can't see it.
对不起这个基本问题,但是我已经多次浏览它了,看不到它。 Cheers again.
再次欢呼。
Assuming the error you are talking about is on this line: 假设您正在谈论的错误在此行上:
if(!formats[field.Name].test(field.value)) {
I'd suggest using a lowercase "n" in the "name" property: 我建议在“名称”属性中使用小写的“ n”:
if(!formats[field.name].test(field.value)) {
JavaScript is case sensitive. JavaScript区分大小写。
UPDATE: In addition to what I've already mentioned, but still regarding case sensitivity, your formats
object has property names with mixed case, eg, First_name
, but the corresponding input elements have a name
attribute in lowercase, eg, name="first_name"
, so when you retrieve an element's name
and try to use it to look up the property in formats
it will return undefined
. 更新:除了我已经提到过,但还是关于区分大小写,您的
formats
对象具有混合的情况下,例如,属性名First_name
,但相应的输入元素有一个name
以小写的属性,例如, name="first_name"
,因此当您检索元素的name
并尝试使用它以formats
查询属性时,它将返回undefined
。 You need to make those match case. 您需要进行匹配。
Fix those errors and it works: http://jsfiddle.net/M4Nzr/ 修正这些错误,它会起作用: http : //jsfiddle.net/M4Nzr/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.