JSFiddle - React, Tailwind, and code Playground

by LyndseyB

HTML

<form data-validate>
  <div> 
    <label> Your Name </label>
    <input type="text" name="yourName" data-name="Your Name" placeholder="enter your name" required data-number />
  </div>
  <div> 
    <label> Your Email </label>
    <input type="text" name="yourEmail" data-name="Your Email" placeholder="enter your email" required data-email />
  </div>
  <input type="button" value="Submit" data-submit />
</form>

CSS

input {
  display: block;
  margin: 1em 0;
}

.required--empty {
   border: 1px #DFACAC solid;
   background-color: #F2DEDE !important;
}

.alert-danger {
    color: #a94442;
    background-color: #f2dede;
    border-color: #ebccd1;
}
.alert-success {
  color: #3c763d;
  background-color: #dff0d8;
  border-color: #d6e9c6;
}
.alert {
    padding: 15px;
    margin: 10px 0;
    border: 1px solid transparent;
    border-radius: 4px;
}

Babel + JSX

const FORMS = (() => {

  // clears any open alerts on screen
  const clearAlerts = (el) => {
    if(!el) return;
    
    let alerts = el.querySelectorAll('.alert');

    [].forEach.call(alerts, (alert) => {
      $(alert).remove();
    });
  };

  // @PRIVATE
  // Creates new alert box HTML
  // @param alertType danger || success
  // @param errorStr string error to be displayed in alert
  const createAlertElement = (alertType, customStr) => {

    let alertTitle = null;
    let defaultStr = null;
    let strAlert = '';
    
    switch(alertType) {
      case 'danger':
        alertTitle = 'Error';
        defaultStr = 'Errors found';
        break;
      case 'success': 
        alertTitle = 'Success';
        defaultStr = 'Success';
        break;
    }

    let strMessage = customStr || defaultStr;

    strAlert = 
      `<div class='alert alert-${alertType}'>
        <a href='#' class='close' data-dismiss='alert'>&times;</a>
        <strong>${alertTitle}!</strong> ${strMessage}
      </div>`;

    return strAlert;
  };

  // @PRIVATE
  // Prepends alert box to the passed in element
  const createAlert = (el, customStr, alertType) => {
    let alert = $(el).find('.alert');

    if(alert.length) {    
      clearAlerts(el);     
    }     

    // create an alert element
    alert = createAlertElement(alertType, customStr);

    // prepend alert to the HTML element
    $(el).prepend(alert);
  } 

  // Form error box
  // @param formElement - ID of form
  // @param customErrorStr (optional) - Custom html to be displayed in alert
  // returns HTML error box
  const showError = (form, customStr = '') => {
    return createAlert(form, customStr, 'danger'); 
  };

  // Form error box
  // @param element to prepend alert to
  // @param customErrorStr (optional) - Custom html to be displayed in alert
  // @param scrollToTop (optional) if user has scrolled, return them to the top of the screen
  // returns HTML success box
  const showSuccess = (form, customStr = '',...