Form Validation
Form Validation
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
</head>
<body>
<form id="loginForm">
<input type="text" name="username" required placeholder="Username" data-error-msg="Username is required"><br><br>
<input type="password" name="password" required placeholder="Password" data-error-msg="Password is required"><br><br>
<input type='text' class='form-control' data-error-msg="Data required" required>
<!-- Additional form fields -->
<button type="button" id="submitForm">Submit</button>
</form>
<div id="result"></div>
</body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$('#submitForm').on('click', function (e) {
e.preventDefault();
// Clear previous errors
$('.error').remove();
// Client-side validation
var form = $('#loginForm')[0];
if (form.checkValidity()) {
$.ajax({
type: 'POST',
url: 'validate.php',
data: $('#loginForm').serialize(),
success: function (response) {
$('#result').html(response);
}
});
} else {
// Display individual field errors (client-side)
for (var i = 0; i < form.length; i++) {
if (!form[i].checkValidity()) {
var fieldName = $(form[i]).attr('name');
console.log(fieldName);
var customErrorMsg = form[i].validationMessage;
$(form[i]).after('<div class="error">' + customErrorMsg + '</div>');
}
}
}
});
});
</script>
</html>
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Server-side validation
$errors = [];
// Validate username
if (empty($_POST['username'])) {
$errors['username'] = "Username is required12345";
}
// Validate password
if (empty($_POST['password'])) {
$errors['password'] = "Password is required";
}
// Add more validation rules for other fields as needed
if (empty($errors)) {
// Simulating successful validation - you can perform further checks here
echo "Validation successful. Proceed with form processing.";
} else {
// If server-side validation fails, send errors for each field
foreach ($errors as $field => $error) {
echo "<div class='error'>$error</div>";
}
}
} else {
echo "Invalid request!";
}
?>
Comments
Post a Comment