I want to add a basic name and email validation JS script to an HTML page, so when submit is pressed it will check multiple fields and throw errors if any are filled incorrectly. Unfortunately, when submit is pressed the page just reloads with fields empty and no error is thrown on the HTML page.
I am still learning JS.
Here is my JS snippet to check for name and email:
//Check if name is anything other than letters or spaces. If it isn't throw error.
function validateForm() {
var validEntry = /[a-zA-Z ]/;
var x = document.forms["clientinfo"]["txtFullName"].value;
if (x.value.match(!validEntry)) {
alert("Invalid name. Please try again.");
document.clientinfo.txtFullName.focus();
return false;
}
// Check if email is in proper format - words@words.com. If it isn't throw error.
var y = document.forms["clientinfo"]["txtEmail"].value;
var validEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})/
if (y.value.match(validEmail)) {
return true
} else {
alert("Invalid email. Please try again.")
document.clientinfo.txtEmail.focus();
return false;
}
}
<div id="inputArea">
<form name="clientinfo" onsubmit="return validateForm()" method="post">
Name:
<input class="Inputinfo" type="text" name="txtFullName" placeholder="John Stewart" required>
<br> Email:
<input class="Inputinfo" type="text" name="txtEmail" placeholder="john@example.com" required>
<br> Phone:
<input class="Inputinfo" type="tel" name="phone" placeholder="XXX-XXX-XXXX" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required>
<br> Description:
<br>
<textarea class="Inputinfo" id="txtDescription" name="description" rows="8" cols="50" placeholder="Please enter any additional client information here."></textarea>
<br>
<input type="submit" value="Enter" id="enterbutton">
</form>
</div>
How can I fix this problem?