JSFiddle - React, Tailwind, and code Playground
HTML
<form class="user-reg-form" action="">
<div class="data-block">
<input type="email" class="email" placeholder="Enter your e-mail" />
<input type="password" class="password" placeholder="Enter password" />
</div>
<div class="console">
<div class="errors"></div>
<div class="warnings"></div>
</div>
<input type="submit" value="Go!" disabled="disabled" />
</form>
CSS
.user-reg-form .data-block input {
display:block;
margin:0 0 5px;
}
.console .errors {
color:red;
}
.console .warnings {
color:green;
}
JavaScript
function Email(emailStr) {
this.re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
this.value = emailStr;
}
Email.prototype.isValid = function() {
return this.re.test(this.value);
}
$(function() {
var $form = $(".user-reg-form");
var logger = new (function($warnings, $errors, wrapFunc) {
this.logWarning = function(msg) {
$warnings.append(wrapFunc(msg));
};
this.logError = function(msg) {
$errors.append(wrapFunc(msg));
};
this.clearWarnings = function() {
$warnings.empty();
}
this.clearErrors = function() {
$errors.empty();
}
})($form.find(".console .warnings"), $form.find(".console .errors"), function (msg) { return "<p>" + msg + "</p>"; });
function validate() {
logger.clearErrors();
logger.clearWarnings();
var isValid = true;
var email = $form.find(".data-block .email").val();
var password = $form.find(".data-block .password").val();
if (!email || email.replace(/\s/g, '').length < 1) {
logger.logError("Email is required.");
isValid = false;
} else {
if (!(new Email(email)).isValid()) {
logger.logWarning("Perhaps e-mail is incorrect.");;
}
}
if (!password) {
logger.logError("Password is required.");
isValid = false;
}
$form.find("[type=submit]").prop('disabled', !isValid);
}
$form.find(".data-block").find(".email, .password").on("keyup change", validate);
validate();
});