Simple Input Validation

by kingkool68

HTML

<label for="example">Enter 4 or more characters</label>
<input type="text" id="example">

CSS

.bad {
color: red;
}

JavaScript

$('input').keyup(function() {
    //Clearout any class set on this element.
    $(this).attr('class', '');
    
    //Get the value of the input
    var val = $(this).val();
    
    //Check to see if there are less than 4 characters entered. If so, add the class 'bad' to the input element.
    if( val.length < 4  ) {
        $(this).addClass( 'bad' );                  
    }
});