使用javascript进行表单验证,即使它应该验证两者,也只验证第一个字段

时间:2015-05-05 06:58:27

标签: javascript php html forms validation

我有一个简单的表单,使用php回显:

echo '<form action="" method="POST" name="newTicket" onsubmit="return validateForm(this)">

<label>Full name*:</label><input type="text" style="width:50%" name="ticket_user_fullname" placeholder="Full name..." > <br /><br />

<label>Email address*:</label><input type="text" style="width:50%" name="ticket_user_email" placeholder="user@domain.com..." >

<input class="btn" type="submit" name="submit" value="submit" >

</form>';

表单正确调用validateForm函数。这是validateForm函数和相关函数:

function validateForm(form){

var reason = "";

reason += validateFullname(form.ticket_user_fullname);
reason += validateEmail(form.ticket_user_email);

  if (reason != "") {
    alert("Some fields need correction:\n" + reason);
    return false;
  }
  return true;
}

function validateFullname(ticket_user_fullname)
{
error = "";
var re = /^[a-zA-Z ]*$/;    

if(ticket_user_fullname.value == "" || ticket_user_fullname.value == null) {
    error = "Full name must not be empty. \n";
    ticket_user_fullname.style.border="1px solid red";
}else if(!re.test(ticket_user_fullname.value)){
    error = "Your name cannot contain numbers or special characters. \n"
    ticket_user_fullname.style.border="1px solid red";
}else{
form.ticket_user_fullname.style.border="1px solid #cccccc";
}       

return error;
}

function validateEmail(ticket_user_email)
{
error = "";
var re = /\S+@\S+\.\S+/;

if(ticket_user_email.value == "" || ticket_user_email.value == null) {
    error = "Email must not be empty. \n";
    ticket_user_email.style.border="1px solid red";
}else if(!re.test(ticket_user_email.value)){
    error = "Your email must be in the format: user@domain.com. \n"
}else{
ticket_user_email.style.border="1px solid #cccccc";
}   

return error;
}

如果未在全名字段中输入任何内容,或者在全名字段中输入了数字,则表单会正确验证。当输入正确的字符串时,它会忽略表单其余部分的验证,并提交表单。

在提交之前,所有字段中的所有数据都应该是正确的。

1 个答案:

答案 0 :(得分:1)

$folderPath = $outputfolder + '\' + $capfile.FullName.Split('\')[3] + '\' + $capfile.FullName.Split('\')[4] + '\'+$capfile.FullName.Split('\')[6] if (!(Test-Path $folderPath)) { Write-Host "Creating folder:" $folderPath New-Item $folderPath -Type Directory } $pngImage = Get-Image -capFile $capfile -folderLoc $folderPath $pngfile = $capfile.BaseName+".png" New-Item -Path $folderPath -name $pngfile -ItemType "file" -Value $pngImage. -force

function validateFullname(ticket_user_fullname)

应为form.ticket_user_fullname.style.border="1px solid #cccccc";

您的表单中应该有一些错误。