简体   繁体   中英

Directive to accept numbers greater than 0 and less than 100

I am trying to create an angular Directive which returns an error when the input of the textfield is less than 5 and greater than 200 i am trying with this code and for some reason it isnt working any help would be appreciated.

JS

app.directive('numbersOnly', function(){
   return {
     require: 'ngModel',
     link: function(scope, element, attrs, modelCtrl) {
       modelCtrl.$parsers.push(function (inputValue) {
           // this next if is necessary for when using ng-required on your input. 
           // In such cases, when a letter is typed first, this parser will be called
           // again, and the 2nd time, the value will be undefined
           if (inputValue == undefined) return '' 
           var transformedInput = inputValue.replace(/[^0-9]/g, ''); 
           console.log("inputValue"+inputValue);
           if(parseInt(inputValue) > 200 || parseInt(inputValue) < 5){
             return '';
           }
           if (transformedInput!=inputValue) {
              modelCtrl.$setViewValue(transformedInput);
              modelCtrl.$render();
           }         

           return transformedInput;         
       });
     }
   };
});

HTML

<div ng-controller="MyCtrl">
        <input type="text" ng-model="number" required="required" numbers-only="numbers-only" />
</div>

The plunker that i created is this ( http://plnkr.co/edit/QKifStiFmHBF8GhcH3Ds?p=preview )

Any help would be appreciated!

I have given a directive that takes care of your model value to always contain int values between 5 and 200. A 'ng-invalid' class will be added when you do setValidity to false. Using that you can use css to display error to the user. In case you want your input to be updated with the correct model value in case of error, you can do it in the blur event.

 app.directive('numbersOnly', function(){
       return {
         require: 'ngModel',
         link: function(scope, element, attrs, modelCtrl) {
           modelCtrl.$parsers.push(function (inputValue) {


           if(parseInt(inputValue) <= 200 && parseInt(inputValue) >= 5){
             modelCtrl.$setValidity('numbersOnly', true);
             return inputValue;
           } else {
             modelCtrl.$setValidity('numbersOnly', false);
             return modelCtrl.$modelValue;
           }

       });
     }
   };
});

angular already has perfect directives for that. all you need is a form and use Min Max inside input tag

<form name="ue.form">
   <input type="number"  ng-model="ue.num" name="num" min="5" max="200" >
</form>
<p ng-if="ue.form.$error">
      number must be less than 200 and greater than 5
</p>
or you can handle each error separately:
<p ng-if="ue.form.num.$error.min">
      number must be  greater than 5
</p>
<p ng-if="ue.form.num.$error.max">
      number must be less than 200
</p>

if number is not in range 5-200 then form validotor throw an error. min and max work only with input type="number".

https://plnkr.co/edit/?p=preview

Here's what I would suggest:

  1. Use ng-model-options="{ updateOn: 'blur' }" so that model gets updated only on blur.
  2. Try this code in directive:

    app.directive('numbersOnly', function(){ return { require: 'ngModel', restrict: 'A', link: function(scope, element, attrs, ngModel) {

      element.on('blur', function() { if (ngModel.$viewValue < 5 || ngModel.$viewValue > 200) { ngModel.$setViewValue(''); element.val(''); } }); } 

    }; });

You can use ng-messages for these kind of validation purposes

We always can customize ng-messages with our needs.

you can create two directives for min and max. In your case your minimum value is 5 and max is 200, we dont need to hardcode our values inside the directives.

You dont need to worry for adding error messages in your directive. ng-messages will do it for you. You just need to put your messages inside ng-messages div.

Directive

 module.directive("min", function () {
        return {
            restrict: "A",
            require: "ngModel",
            link: function (scope, element, attributes, ngModel) {
                ngModel.$validators.min = function (modelValue) {
                    if (!isNaN(modelValue) && modelValue !== "" && attributes.min !== "")
                        return parseFloat(modelValue) >= attributes.min;
                    else
                        return true;
                }
            }
        };
    });

  module.directive("max", function () {
        return {
            restrict: "A",
            require: "ngModel",
            link: function (scope, element, attributes, ngModel) {
                ngModel.$validators.max = function (modelValue) {
                    if (!isNaN(modelValue) && modelValue !== "" && attributes.max !== "")
                        return parseFloat(modelValue) <= attributes.max;
                    else
                        return true;
                }
            }
        };
    });

Usage

<form name="myform">
 <input type="text" name="minmax" ng-model="number" required="required" min="5" max="200"/>
 <div data-ng-messages="myform.minmax.$error" class="error-messages">
  <div data-ng-message="min">YOu cant enter below 5</div>
   <div data-ng-message="max">You cant enter above 200</div>
  </div>
</form>

Here is my pluker example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM