I'm having trouble validating multiple textfields with a single javascript function. The function only validates 2 textfields leaving the other, yet validation for all of them are well written. Please help!
function validate(form){
var name = document.getElementById("SNameValue").value;
var email = document.getElementById("SEmailValue").value;
var emailvalid = /^([a-zA-Z0-9\.-]+)@([a-zA-Z0-9-]+).([a-z]{2,5})(.[a-z]{2,5})$/;
var phoneNum = document.getElementById("SPhoneValue").value;
var phoneValid = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
var suburb = document.getElementById("SsuburbValue");
var message = document.getElementById("SMessageValue").value;
//name validation
if(name==""){
alert("Enter your name, please");
return false;
}
//email validation
if (email==""){
alert("Enter your email address, please");
return false;
}
if(email.match(emailvalid)){
return false;
}
//phone number validation
if(phoneNum==""){
alert("Enter your phone number, please");
return false;
}
if (phoneNum.match(phoneValid)){
return false;
} else{
alert("Enter a valid phone number with 10 digits, please");
return false;
}
//suburb validation
if (suburb.selectedIndex==0){
alert("Select your suburb, please");
return false;
}
//message validation
if(message==""){
alert("Enter a message, please");
return false;
}
//display everything
else{
alert("Name: "+name+"\nEmail: "+email+"\nPhone number: "+phoneNum+"\nSuburb: "+suburb+"Message: "+message);
return false;
}
return true;
} ```
HTML code:
``` <form onSubmit="return validate(this)" action="" method="Post">
Name<br>
<input type="text" id="SNameValue" placeholder="Enter Name"><br>
Email<br>
<input type="email" id="SEmailValue" placeholder="Enter Email"><br>
Phone Number<br>
<input type="tel" id="SPhoneValue" placeholder="Enter Phone number"><br>
Suburb<br>
<select name="suburbList" id="SsuburbValue">
<option disabled selected value="">Select your suburb -- </option>
<option value="Atlantic Seaboard">Atlantic Seaboard</option>
<option value="Cape Flats">Cape Flats</option>
<option value="City Bowl">City Bowl</option>
<option value="Helderberg">Helderberg</option>
<option value="NothernSuburb">NothernSuburb</option>
<option value="South Peninsula">South Peninsula</option>
<option value="Southern Suburb">Southern Suburb</option>
<option value="West Coast">West Coast</option>
</select><br>
Message<br>
<textarea rows="3" id="SMessageValue" placeholder="How can we help you"></textarea><br>
<button class="button1" type="submit">Send me a Quote</button>
</form>
I expect the function to verify and validate all the textfields, but it only validates the first 2 textfields.