JSFiddle - React, Tailwind, and code Playground

Form Field Validation

by Jennifer Perrin

HTML

<form method="#">
    <input type="text" class="textbox" />
    <input type="text" class="textbox" />
    <input type="text" class="textbox" />
    <input type="text" class="textbox" />
    <input type="text" class="textbox" />
    <button type="submit" value="submit">submit</button>
</form>

CSS

input[type=text] {
    display:block;
    float:left;
    height:30px;
    width:190px;
    clear:both;
    margin:8px 0 0 15px;
    outline:0;
    border:1px solid #666;
    box-shadow:inset 0 0 2px #ccc;
}
button {
    margin:7px 0 0 20px;
    padding:4px 8px;
    font:15pt 'Georgia';
}
.warning {
    background:rgba(255,0,0,.2);
    border:1px solid #F50C43 !important;
}

JavaScript

$(':input').blur(function() {
    if(!$.trim(this.value).length) {
        $(this).addClass('warning');
    } else {
        $(this).removeClass('warning');
    }
});

$('form').on('submit', function(e) {
    $(':input').each(function() {
        if ( $(this).val() === "" ) {
            $(this).addClass('warning');
            e.preventDefault();
        } else {
            return true;
        }
        if ( $(':input').hasClass('warning') ) {
            e.preventDefault();
        } else {
            return true;
        }
    });
});