← back

Using an angular directive for a form required polyfill

December 30, 2014
software development

I needed a simple polyfill for handling the HTML5 required input attribute. I created this simple Angular directive for forms that checks for the required attribute in older browser that don’t support HTML5 form validation.

It basically works by checking for forms with inputs that have the required attribute, checks them for content and cancels the form submit in case one of the required fields is not filled.

.directive(‘form’, function(){ return { restrict: ‘E’, link : function(scope, element, attrs){ var requiredElements = $(element).find(‘input[required]‘); if(requiredElements.length){ if(typeof requiredElements[0].checkValidity !== ‘function’){ $(element).on(‘submit’, function(){ var requiredValid = true; angular.forEach(requiredElements, function(el){ if(el.value == “) { requiredValid = false; $(el).addClass(‘error’); } }); return requiredValid; }) } } } }; })

This implementation uses jQuery since I had this available in my environment anyway, it can easily be changed to vanilla JS.

comments powered by Disqus