JSFiddle - React, Tailwind, and code Playground

by Varun Krishna P

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">
    <form name="form" valid-submit="sendFormToServer()" novalidate>
        <label for="name" ng-class="{'error': form.$submitted && form.name.$invalid}">name</label>
        <input id="name" name="name" type="text" required ng-model="name"></input>
        <button type="submit">log in!</button>
        
        <div class="help" ng-show="form.$submitted && form.name.$invalid">(name is required)</div>
    </form>
</div>

CSS

.form-group .alert {
  padding: 0px;
  margin-bottom: 0px;
}

.error {
    color: red;
}

.help {
    color: gray;
}

JavaScript

var app = angular.module('app', []);

// directive that prevents submit if there are still form errors
app.directive('validSubmit', [ '$parse', function($parse) {
		return {
			// we need a form controller to be on the same element as this directive
			// in other words: this directive can only be used on a &lt;form&gt;
			require: 'form',
			// one time action per form
			link: function(scope, element, iAttrs, form) {
				form.$submitted = false;
				// get a hold of the function that handles submission when form is valid
				var fn = $parse(iAttrs.validSubmit);
				
				// register DOM event handler and wire into Angular's lifecycle with scope.$apply
				element.on('submit', function(event) {
					scope.$apply(function() {
						// on submit event, set submitted to true (like the previous trick)
						form.$submitted = true;
						// if form is valid, execute the submission handler function and reset form submission state
						if (form.$valid) {
							fn(scope, { $event : event });
							form.$submitted = false;
						}
					});
				});
			}
		};
	}
]);

app.controller('MainCtrl', function($scope) {
  $scope.sendFormToServer = function() {
    alert('sending to server...');
  };
});