FORM VALIDATION IN JAVA SCRIPT

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 1

//FORM VALIDATION IN JAVA SCRIPT

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<script>
function validateForm() {
// Access form fields
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;

// Define regular expressions for validation


var nameRegex = /^[a-zA-Z\s]*$/; // Only letters and spaces
var emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; // Email format

// Validate name field


if (!name.match(nameRegex)) {
alert("Please enter a valid name");
return false; // Prevent form submission
}

// Validate email field


if (!email.match(emailRegex)) {
alert("Please enter a valid email address");
return false; // Prevent form submission
}

// Form is valid, allow submission


return true;
}
</script>
</head>
<body>

<h2>Form Validation Example</h2>

<form id="myForm" onsubmit="return validateForm()">


<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>

</body>
</html>

You might also like