简体   繁体   中英

Form validation using javascript, validates only the first field even though it should be validating both

I have a simple form which is echoed using 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>';

The form calls the validateForm function correctly. This is the validateForm function and the relating functions:

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;
}

The form is validated correctly when nothing is entered into the full name field, or when there is a number entered into the full name field. When there is a correct string input, it ignores the validation on the rest of the form and the form is submitted.

what should happen is all data in all of the fields should be correct before submission.

In your function validateFullname(ticket_user_fullname)

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

It should be ticket_user_fullname.style.border="1px solid #cccccc";

Some error should be made in your form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM