Skip to content

Add Validate Range #1

Description

@lancevo

a snippet from angular directive, should integrate in smartform structure and html5 min/max attributes

angular.module('app')
.directive('validateRange', function () {
return {
restrict: 'A',
link: function postLink(scope, element, attrs) {

    var vrAttrs = attrs.validateRange.split(','),
        a, b, container;

    // validate params
    if (vrAttrs.length < 2) {
      throw new Error('Validate Range requires at least 2 numbers ' + attrs.validateRange)
    }

    a = parseFloat(vrAttrs[0]);
    b = parseFloat(vrAttrs[1]);

    container = vrAttrs.length == 3 ? vrAttrs[2] : undefined;

    if (container) {
      container = $(element).closest(container);
    } else {
      container = $(element).parent();
    }

    $(element).on('focusin focusout keyup', function(e){
       var value = parseFloat($(element).val());

      switch(e.type) {
        case 'focusin' :
        case 'keyup' :
          container.addClass('focus');
          if (value >= a && value <=b) {
            container.removeClass('invalid-range').addClass('valid-range');
          }
          break;
        case 'focusout' :
          if (value >= a && value <=b) {

            container.removeClass('invalid-range').addClass('valid-range');
          } else {
            container.removeClass('valid-range').addClass('invalid-range');
          }
          container.removeClass('focus').addClass('visited');
      }
    })

  }
};

});

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions