JSFiddle - React, Tailwind, and code Playground
HTML
<form action="#submit">
<input type="text" id="comment-name" name="name" placeholder="Enter your name" />
<input type="email" id="comment-email" name="email" placeholder="Enter your email address" />
<textarea name="comment-area" id="comment-area" placeholder="Add your comment…"></textarea>
<button type="submit" class="square-button">Add Your Comment</button>
</form>
CSS
body {
background: #000000;
color: #222;
}
textarea,input {
color: #000;
background: #fff;
border: 1px solid #bbb;
width: 300px;
padding: 5px 10px;
display:block;
margin: 10px 0;
}
textarea { min-height: 200px; }
.error {
color: red !important;
border: 1px solid red !important;
}
.valid {
color: green !important;
border: 1px solid green !important;
}
JavaScript
(function($){
$.fn.validate = function( opts ) {
var o = $.extend( {} , $.fn.validate.settings , opts );
return this.each(function() {
var form = $(this); // the form element!
var regex = {
text : /.+/gi,
email : /^(\w|\.|-)+?@(\w|-)+?\.\w{2,4}($|\.\w{2,4})$/i,
number : /^\d+$/
}
var fields = $(':input[type!="hidden"][type!="submit"][type!="clear"]', form);
// catch the submit and check stuff.
form.submit(function(e) {
var isValid = true;
var failed = [];
var passed = [];
$.each( fields , function(i, el) {
var type = ( el.type === undefined || el.type === 'textarea' ? 'text' : el.type );
var el = $(el);
// remove classes
el.removeClass( o.valid ).removeClass( o.error );
// test values
if ( !regex[type].test( el.val() ) ) {
// failed
console.log('failed:', el, el.val(), regex[type], regex[type].test( el.val() ) );
failed.push(el);
isValid = false;
} else {
// passed
passed.push(el);
}
});
// if validation failed
if ( !isValid ) {
e.preventDefault();
$.each( failed , function(i, el) {
$(el).addClass(o.error);
});
$.each( passed , function(i, el) {
$(el).addClass(o.valid);
});
}
});
// as you type validation on...