Step of Name Validation
- Create a Checkbox form
- Write the Checkbox validation code
Create a Checkbox form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rays Coding-JQuery Validation</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container mt-5 form_box">
<div class="row">
<div class="card p-0">
<div class="card-header bg-primary">
<h3 class="text-center text-white">Rays Coding :- JQuery Form Validation(Checkbox)</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-lg-12">
<form action="#" method="post" enctype="multipart/form-data">
<div class="row check_id">
<div class="col-lg-6">
<div class="mb-3">
<div class="form-check">
<input class="form-check-input identity_class identity" name="user_identity[]" type="checkbox" value="php" id="useridentity1">
<label class="form-check-label ">PHP</label>
</div>
<div class="form-check">
<input class="form-check-input identity_class identity" type="checkbox" name="user_identity[]" value="python" id="useridentity2">
<label class="form-check-label ">Python</label>
</div>
</div>
</div>
<div class="col-lg-6">
<div class="mb-3">
<div class="form-check">
<input class="form-check-input identity_class identity" name="user_identity[]" type="checkbox" value="java" id="useridentity3">
<label class="form-check-label ">Java</label>
</div>
<div class="form-check">
<input class="form-check-input identity_class identity" name="user_identity[]" type="checkbox" value="javascript" id="useridentity4">
<label class="form-check-label ">Javascript</label>
</div>
</div>
</div>
<span id="useridentity_error" class="useridentityerror"></span>
</div>
<div class="row">
<div class="col-lg-4">
<button type="submit" class="btn btn-primary mt-4" name="sub_btn" id="sub_button">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-12 validationtext">
<h1>jQuery Checkbox Validation</h1>
</div>
</div>
</div>
<!-- jquery CDN -->
<script src="https://code.jquery.com/jquery-3.6.2.slim.min.js" integrity="sha256-E3P3OaTZH+HlEM7f1gdAT3lHAn4nWBZXuYe89DFg2d0=" crossorigin="anonymous"></script>
</body>
</html>
Write the Checkbox validation code
<script>
$(document).ready(function () {
$('#sub_button').on('click', function () {
var field = $('input[type="checkbox"]').serializeArray();
if (field.length == 0) {
$('#useridentity_error').text('Please Select Any One Option.');
$('#useridentity_error').css('color', 'red');
return false;
}
});
});
</script>