我一直在尝试使用Javascript验证此表单,但是由于一些奇怪的原因,只有第一个输入字段似乎正在做它应该做的事情。这是相关的代码片段:
<form method="post" name="myform" action="www.google.com" onsubmit="return validateForm(this);"> <h3 id="secondarytext"><strong>Your details:</strong></h3> <div class="label1"> <label for="firstName">First Name</label> <input type="text" id="name" name="name" onblur="validateName(name)" /> <span id="nameError" style="display: none;">Please enter your name, you can only use alphabetic characters</span> <label for="ssurname" >Surname</label> <input type="text" id="surname" name="surname" onblur="validateSurname(surname)" /> <br /> </div> <input type="reset" value="Reset Form"> <input type="submit" value="Submit"> </form>
使用Javascript:
function validateName(x)
{
var re = /^[A-Za-z]{2,25}$/;
if(re.test(document.getElementById(x).value)){ /* This checks the input's value corresponds with the regular expression (re) */
document.getElementById(x).style.background ='#ccffcc'; /* If it does it changes the background colour of the field to green*/
document.getElementById(x).style.border="4px solid #ccffcc";
document.getElementById(x + 'Error').style.display = "none"; /* This hides the error message because the function returned as true */
return true;
}
else{ /* If the function doesn't return as true this is what happens */
document.getElementById(x).style.background ='#e35152'; /* The background colour of the field changes to red */
document.getElementById(x).style.border="4px solid #e35152";
document.getElementById(x + 'Error').style.display = "block"; /* This displays the error message */
return false;
}
}
function validateSurname(x)
{
var re = /^[A-Za-z]{2,25}$/;
if(re.test(document.getElementById(x).value)){
document.getElementById(x).style.background ='#ccffcc';
document.getElementById(x + 'Error').style.display = "none";
return true;
}
else{
document.getElementById(x).style.background ='#e35152';
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
function validateForm()
{
var error = 0;
if(!validateName('name'))
{
document.getElementById('nameError').style.display = "block";
error++;
}
if(!validateSurname('surname'))
{
document.getElementById('surnameError').style.display = "block";
error++;
}
if(error > 0)
{
return false;
}
else if(error < 0) {
return true;
}
}
答案 0 :(得分:0)
也许这些更改会对您有所帮助:
1)添加您想要在姓氏错误时显示的错误消息:
<label for="ssurname" >Surname</label>
<input type="text" id="surname" name="surname" onblur="validateSurname('surname')" /> <br />
<span id="surnameError" style="display: none;">Please enter your surname, you can only use alphabetic characters</span>
2)将字符串传递给参数而不是javascript var(例如,执行validateSurname('surname')
而不是validateSurname(surname)
),因为您定义的函数期望字符串作为参数。