JSFiddle - React, Tailwind, and code Playground
by David Buzatto
HTML
<form id="myForm">
Name: <input id="name" type="text" allowblank="false" max="10"/><span for="name" class="errorMessage"></span>
<br/>
Age: <input id="age" type="text" allowblank="false"/><span for="age" class="errorMessage"></span>
<br/>
<input type="submit" value="Save"/>
</form>
CSS
.error {
border-color: #ff0000;
}
.errorMessage {
color: #ff0000;
}
JavaScript
// form validation
$( "#myForm" ).submit(function(){
return validate( $(this) );
});
function validate( $form ) {
var isValid = true;
$textInputs = $form.find( "input[type=text]" );
$textInputs.each(function( index, item ){
var isThisValid = true;
var $item = $(item);
var $errorSpan = $( "span[for=" + $item.attr("id") + "]" );
var max = parseInt( $item.attr( "max" ) );
if ( $item.attr( "allowblank" ) == "false" ) {
if ( $item.val().trim() == "" ) {
$item.addClass( "error" );
$errorSpan.html( "this field cannot be empty" );
isThisValid = false;
}
}
if ( max && isThisValid ) {
if ( $item.val().trim().length > max ) {
$item.addClass( "error" );
$errorSpan.html( "the maximum length of this field is " + max );
isThisValid = false;
}
}
if ( isThisValid ) {
$item.removeClass( "error" );
$errorSpan.html( "" );
}
if ( isValid && !isThisValid ) {
isValid = false;
}
});
return isValid;
}