Formatting and Validating Form AngularJS 1.4

869 views Asked by At

I am building a form using angularjs, and I have got a amount field in it.

I want to validate and format the amount so, that invalid amount is restricted and only valid amount should be entered, rest all should be discarded. Valid amount are:

1.23 0.99

so, basically, 1 digit followed by 2 decimal points.

I am confused to use between filters or directives, as I have never used any of them. I would appreciate, If anyone has done similar thing in past and if you can share with me or if you can give me solution.

I have used ng-pattern like this ng-pattern="/^[0-9]*\.[0-9][0-9]$/ but doesn't work for me.

I am using AngularJS 1.4 latest version.

EDIT - MY DODE

    <input type="number"
  name="globalNetPrice"
  value="{{netprice.globalNetPrice}}"
  ng-model="netprice.globalNetPrice"
  class="form-control"
  required
  ng-minlength="0.01"
  ng-maxlength="999"
  ng-pattern="/^[0-9]+.[0-9][0-9]$/"
  >

<p ng-show="netpriceForm.globalNetPrice.$invalid && !netpriceForm.globalNetPrice.$pristine">

<small class="error" ng-show="netpriceForm.globalNetPrice.$error.required">Net Price is required.</small>

<small class="error" ng-show="netpriceForm.globalNetPrice.$error.number">That is not a Net Price. Please input a valid Net Price.</small>

<small class="error" ng-show="netpriceForm.globalNetPrice.$error.pattern">That is not a valid Net Price. Pattern not valid.</small>

</p>
2

There are 2 answers

0
Mahesh Verma On

You also use directive for this :-

     app.directive('numberOnly', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            ngModel: '='
        },
        link: function (scope) {
            scope.$watch('ngModel', function (newValue, oldValue) {
                if (oldValue != undefined && oldValue.length > 0) {
                    if (newValue != undefined) {
                        if (typeof newValue == 'string') {
                            var notNumberCheck = newValue.replace(oldValue, '');
                            if (isNaN(newValue)) {
                                if (notNumberCheck != '.') {
                                    scope.ngModel = oldValue;
                                    return;
                                }
                            }
                        }
                    } else {
                        scope.ngModel = "";
                        return;
                    }
                } else {
                    if (isNaN(newValue) && newValue != '.') {
                        scope.ngModel = "";
                        return;
                    }
                }
                var arr = String(newValue).split("");
                if (arr.length === 0) return;
                if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.')) return;
                if (arr.length === 2 && newValue === '-.') return;
                if (isNaN(newValue)) {
                    scope.ngModel = oldValue;
                }
            });
        }
    };
})

0
Navaneet On

Angularjs has currency filter which you can use easily.

Also check this stackoverflow question Here is working fiddle

app.directive('currencyInput', function() {
return {
    restrict: 'A',
    scope: {
        field: '='
    },
    replace: true,
    template: '<span><input type="text" ng-model="field"></input>{{field}}</span>',
    link: function(scope, element, attrs) {

        $(element).bind('keyup', function(e) {
            var input = element.find('input');
            var inputVal = input.val();

            //clearing left side zeros
            while (scope.field.charAt(0) == '0') {
                scope.field = scope.field.substr(1);
            }

            scope.field = scope.field.replace(/[^\d.\',']/g, '');

            var point = scope.field.indexOf(".");
            if (point >= 0) {
                scope.field = scope.field.slice(0, point + 3);
            }

            var decimalSplit = scope.field.split(".");
            var intPart = decimalSplit[0];
            var decPart = decimalSplit[1];

            intPart = intPart.replace(/[^\d]/g, '');
            if (intPart.length > 3) {
                var intDiv = Math.floor(intPart.length / 3);
                while (intDiv > 0) {
                    var lastComma = intPart.indexOf(",");
                    if (lastComma < 0) {
                        lastComma = intPart.length;
                    }

                    if (lastComma - 3 > 0) {
                        intPart = intPart.splice(lastComma - 3, 0, ",");
                    }
                    intDiv--;
                }
            }

            if (decPart === undefined) {
                decPart = "";
            }
            else {
                decPart = "." + decPart;
            }
            var res = intPart + decPart;

            scope.$apply(function() {scope.field = res});

        });

    }
};

});