Validate form using jQuery

Created at 20-Mar-2024 , By samar

Create a file name index.html and copy/paste below code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <style>
        p{
            margin: 0px;
        }
        .has-error, .error-msg{
            font-weight: 600;
        }
    </style>
</head>
<body>
    
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <h1 class="text-center"> Customer Form </h1>
            </div>
            <div class="col-md-12">
                <form action="insert.php" method="post" id="PartForm">
                    <div class="row">
                        <div class="col-md-4 offset-4">
                            <div class="mb-3">
                                <label for="customer_name" class="form-label">Customer Name</label>
                                <input type="text" class="form-control" id="customerName" name="customer_name"/>
                                
                            </div>
                            <div class="mb-3">
                                <label for="mobileNumber" class="form-label">Mobile Number</label>
                                <input type="text" class="form-control" name="mobile" id="mobileNumber">
                            </div>

                            <div class="mb-3">
                                <label for="partQuantity" class="form-label">Product Quantity</label>
                                <input type="text" class="form-control" name="part_quantity" id="partQuantity">
                            </div>

                        </div>
                    </div>

                    <div class="col-md-12">
                        <h3 class="text-center"> Product List </h3>
                        <table class="table table-bordered" id="PartTable">
                            <thead>
                                <tr>
                                    <th scope="col">Particular Name</th>
                                    <th scope="col">Quantity</th>
                                    <th scope="col">Price</th>
                                    <th scope="col">Total Amount</th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                        <div class="error-msg product-error text-danger text-end"></div>
                    </div>

                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="validate.js"></script>
</body>
</html>

Now Create validate.js file and copy/paste below code in it

$(document).ready(function(){
    $('#partQuantity').on('input', function(){
        var thisElem = $(this);
        var partQuantity =  $(this).val();
        thisElem.parent().find('.text-danger').remove();
        if(!$.isNumeric(partQuantity) || partQuantity < 1 || partQuantity > 10){
            $(this).after('<p class="small text-danger error-msg">Please provide a number and it should be in between 1 to 10!</p>')
            return false;
        }

        htmlTr = `<tr><td><input type="text" name="part_name[]" class="form-control part_name"/></td>
                        <td><input type="text" name="part_quantity[]" class="form-control part_quantity"/></td>
                        <td><input type="text" name="part_price[]" class="form-control part_price"/></td>
                        <td><input type="text" name="total_amount[]" class="form-control total_amount" readonly/></td>
                    </tr>`;

        var partItems = $('#PartTable').find('tbody tr').length;
        var newItemCount = (partQuantity - partItems); 

        if(partQuantity > partItems){
            while(newItemCount > 0){
                $('#PartTable').find('tbody').append(htmlTr);
                newItemCount--;
            }
        }else if(partQuantity < partItems ){
            $('#PartTable > tbody  > tr').each(function(index, tr) { 
                if(!$(this).hasClass('filled')){
                    $(this).remove();
                }
            });
            var partItems = $('#PartTable').find('tbody tr').length;
            var newItemCount = (partQuantity - partItems);
            while(newItemCount > 0){
                $('#PartTable').find('tbody').append(htmlTr);
                newItemCount--;
            }
        }

        validateProductInput();
        
    });
});

$('#customerName, #mobileNumber').on('input', function(){
    validateInput($(this));
});

function validateForm(){
    var CustName = $('#customerName');
    var mobileNumberElem = $('#mobileNumber');
    var partQuantityElem = $('#partQuantity');
    CustName.parent().find('.error-msg').remove();
    mobileNumberElem.parent().find('.error-msg').remove();
    partQuantityElem.parent().find('.error-msg').remove();
    $('.product-error').text('');
    var custNameVal = $.trim(CustName.val());
    var MobileNumberVal  = $.trim(mobileNumberElem.val());
    var regexCustName = /^[A-Za-z\s]+$/;
    //var regexCustName = /(?<=[A-Z])[a-z]|(?<=[a-z])[A-Z]/;
    var regexMobile = /^\d{10}$/;
    var partQuantity = partQuantityElem.val();

    isValid = true;
    if(custNameVal == ''){
        showErrorMsg(CustName, 'Please enter customer name!');
        isValid = false;
    }
    else if(!custNameVal.match(regexCustName))
    {
        showErrorMsg(CustName, 'Please provide only alphabets and spaces!');
        isValid = false;
    }else if(custNameVal.length > 15){
        showErrorMsg(CustName, 'Customer name should not be greater than 15 characters !');
        isValid = false;
    }

    if(!regexMobile.test(MobileNumberVal)){
        showErrorMsg(mobileNumberElem, 'Please provide accurate mobile number !');
        isValid = false;
    }
    
    if(!$.isNumeric(partQuantity) || partQuantity > 10 || partQuantity < 0 ){
        showErrorMsg(partQuantityElem, 'Please provide a number and it should be in between 1 to 10!');
        isValid = false;
    }

    if(!validateProductInput()){
        isValid = false;
    }

    return isValid;

}

function validateInput(inputField){
    
    hideErrorMsg(inputField);
    var elementId = $(inputField).attr('id');
    var inputValue = $.trim($(inputField).val());
    var regexCustName = /^[A-Za-z\s]+$/;
    var regexMobile = /^\d{10}$/;

    if(inputValue == '' && elementId == 'customerName'){
        showErrorMsg(inputField, 'Please enter customer name!');
    }else if(!inputValue.match(regexCustName) && elementId == 'customerName'){
        showErrorMsg(inputField, 'Please provide only alphabets and spaces!');
    }else if(inputValue.length > 15 && elementId == 'customerName'){
        showErrorMsg(inputField, 'Customer name should not be greater than 15 characters!');
    }

    if(!regexMobile.test(inputValue) && elementId == 'mobileNumber'){ 
        showErrorMsg(inputField, 'Please provide accurate mobile number !');
    }
}

function showErrorMsg(element, message){
    $(element).after('<p class="small text-danger error-msg">'+message+'</p>');
}

function hideErrorMsg(element){
    $(element).parent().find('.error-msg').remove();
}

$(document).on('keyup',  '#PartTable tbody tr input' , function(){
    $(this).closest('tr').addClass('filled');
});


function validateProductInput(){
    error = 0;
    $('#PartTable > tbody > tr').each(function(){
        var inputVal = $.trim($(this).find('input').val());
        var partQuantity = $.trim($(this).find('.part_quantity').val());
        var partPrice = $.trim($(this).find('.part_price').val());

        if(inputVal == '' || (partQuantity == '' || !$.isNumeric(partQuantity) || (partQuantity > 20 ||  partQuantity < 1)) ||  (partPrice == '' || !$.isNumeric(partPrice) || (partPrice < 1 || partPrice > 200000))  ) {
            error++;
        } 
    });

    if(error > 0){
        $('.product-error').text('Please fill all the product details with valid information!');
        return false;
    }else{
        $('.product-error').text('');
        return true;
    }

    //return (error > 0) ? false : true;
}

$('#PartForm').on('submit', function(e){
    if(!validateForm()){
        e.preventDefault();
    }
});

//Product input validation and update total amout on change quantity and price
$(document).on('keyup', '.part_quantity, .part_price, .part_name', function(){
    var currElement = $(this);
    var currVal = $.trim($(this).val());
    currElement.parent().find('.has-error').remove();
    if(currElement.hasClass('part_quantity') && !$.isNumeric(currVal)){
        currElement.parent().append('<p class="text-danger has-error small"> Please enter number!</p>');
    }else if(currElement.hasClass('part_quantity') && (currVal > 20 ||  currVal < 1 )){
        currElement.parent().append('<p class="text-danger has-error small"> Number should be in between 1 to 20!</p>');
    }

    if(currElement.hasClass('part_price') && !$.isNumeric(currVal)){
        currElement.parent().append('<p class="text-danger has-error small">Please enter number!</p>');
    }else if(currElement.hasClass('part_price') && (currVal < 1 || currVal > 200000)){
        currElement.parent().append('<p class="text-danger has-error small">Product price should be in between 1 to 200000</p>');
    }

    var partQuantity = currElement.closest('tr').find('.part_quantity').val();
    var partPrice = currElement.closest('tr').find('.part_price').val();
    var total_amount = partQuantity * partPrice;
    //console.log(partQuantity);

    currElement.closest('tr').find('.total_amount').val(total_amount);

    validateProductInput();

});

Create insert.php file and copy/paste code in it.

<?php

echo "form submited !";

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.