I have a problem. The code keeps displaying "Last name does not allow number" even when the input is "abc" without any number inside. Can you guys help me to correct it? However, the first name and the email is working fine but I want to have a regex that can validate the email to see if it is in correct format or not.
var check_form=document.getElementById("registration");
var reset_form=document.getElementById("cancel");
var pattern=/^[a-zA-Z\s]+$/gi;
function check(event){
var first_name=document.getElementById("first_name");
var last_name=document.getElementById("last_name");
var email=document.getElementById("email");
event.preventDefault();
if(first_name.value==""){
alert("First name needs to be specified");
first_name.focus();
}
else{
if(!pattern.test(first_name.value)){
alert("First name does not allow number");
first_name.focus();
}
}
if(last_name.value==""){
alert("Last name needs to be specified");
last_name.focus();
}
else{
if(!pattern.test(last_name.value)){
alert("Last name does not allow number");
last_name.focus();
}
}
if(email.value==""){
alert("Email needs to be specified");
email.focus();
}
if(first_name.value!=="" && last_name.value!==""&&email!==""&&pattern.test(first_name.value)&&pattern.test(last_name.value)){
alert("Perfect");
}
}
function resetInfo(){
check_form.reset();
}
check_form.addEventListener("submit",check);
reset_form.addEventListener("click",resetInfo);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Registration Page</title>
<script src="./script.js" defer></script>
<link rel="stylesheet" href="./style.css"/>
<link href="https://fonts.googleapis.com/css2?family=PT+Sans&display=swap" rel="stylesheet">
</head>
<body>
<form name="registration" id="registration">
<p>Registration Form</p>
<div id="firstname">
<label for="first_name">First Name</label>
<input type="text" value="" id="first_name" placeholder="Enter your first name">
</div>
<div id="lastname">
<label for="last_name">Last Name</label>
<input type="text" value="" id="last_name" placeholder="Enter your last name">
</div>
<div id="emailuser">
<label for="email">Email</label>
<input type="email" value="" id="email" placeholder="Enter your email">
</div>
<input type="submit" class="button_submit" value="Submit Here"><br>
<input type="button" id="cancel" class="button_submit" value="Cancel">
</form>
</body>
</html>