0

I have a textfield on my angular js form for the Sale Price of an item. This field is not required, however I want it to be validated for valid number/decimal input > 0 if the user puts a value in the field. Any invalid input should force the field to revert back to 0.00M decimal.

I've tried a few different variations on my basic validNumber directive but I can't get it work. My directive works fine if I wanted the value to always be required for input.

Here's the directive I'm using now for the RetailPrice which is required. I've chopped out the code I added, since it wasn't working anyways.

app.directive('validNumber', function () {
    return {
        require: "ngModel",
        link: function (scope, elm, attrs, ctrl) {
            var regex = /^\d{1,3}(,\d{3})*(\.\d+)?$/;
            var validator = function (value) {
                ctrl.$setValidity('validNumber', regex.test(value));
                return value;
            };
            ctrl.$parsers.unshift(validator);
            ctrl.$formatters.unshift(validator);
        }
    };
});

1 Answer 1

1
<label class="span5"> Username:<span style="color: red" ng-show="manageupdateuser.loginname.$error.required" >*</span></label>
            <div class="span6">
                <input class="span12" type="text" name="loginname" ng-model="oldusername" ng-pattern="/^[a-zA-Z]+$/" ng-minlength="2" ng-maxlength="25" required>
                <span style="color: red" ng-show="manageupdateuser.loginname.$error.minlength">Allow minimum 2 characters.</span>
                <span style="color: red" ng-show="manageupdateuser.loginname.$error.maxlength">Allow maximum 25 characters.</span>
                <span style="color: red" ng-show="manageupdateuser.loginname.$error.pattern">Any other symbol are not allow.</span>
            </div>    

This is demo for only allow a-z and A-z or minimum and maximum length...
also digit or ohter special char are not allow...
You not specified which type of validation you need...

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for fast response sir. This would work great for alphanumeric, however I'm looking for numeric/decimal validation for value.
you only change ng-pattern ....write a regular expression for your need..it's work directly
ng-pattern="/^[1-9]\d*(\.\d+)?$/" add this validation it's work fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.