JSFiddle - React, Tailwind, and code Playground

My Form Validation Script With Basic Fields

by refhat

HTML

<form>
    <input type="text" class="required">
    <br>
    <input type="text" class="required">
    <br>
    <input type="submit" value="ok">
</form>

JavaScript

function validatemyForm() {
    var is_ok = true;

    $('span').remove(); // Remove all existing spans

    $('.required').each(function() {

        if($(this).val() == ""
        || $(this).val().replace(/\s/g, '').length == 0) {

            // Add a span if not filled in, also set is_ok to false
            $(this).after('<span>This is a Required Filed</span>');
            is_ok = false;

        }

    });

    return is_ok; // Return is_ok, which is true by default and
                  // became false when there was a field not filled
                  // in
}

$('form').submit(validatemyForm);