3

I am using input type="number" but I am getting the view as up and down value bars in the text box. How to avoid this?
How can I validate a negative value in the input text box?. If I enter a negative value as input then proper error message should display.

2
  • I wrote this simple directive recently for another question, exactly for your purpose: validating positive numbers. Check it out: stackoverflow.com/a/34095586/949476 Commented Dec 7, 2015 at 12:53
  • Duplicate of stackoverflow.com/questions/3790935/… And for negative numbers You can write a filter that catches minus sign and gives the error message . Commented Dec 7, 2015 at 12:55

1 Answer 1

3

but I am getting the view as up and down value bars in the text box. How to avoid this?

You can remove those spinner buttons in some browsers with simple CSS:

input[type='number'] {
    -moz-appearance:textfield;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
}

(credits to this answer). It will not work in IE though.

Now real question, how to validate user input? Angular solution in this case would be creating additional validation directive. Here is the simple one I recently wrote:

angular.module('demo', []).directive('positive', [function() {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            if (!ctrl) return;
            ctrl.$validators.positive = function(value) {
                return value && value >= 0;
            };
        }
    };
}]);
input[type='number'] {
    -moz-appearance:textfield;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
}

.error {color: brown;}
<script src="https://code.angularjs.org/1.3.0/angular.js"></script>

<div ng-app="demo">
    
    <form name="paymentForm">
        <input type="number" name="amount" ng-model="amount" positive />
    </form>
    
    <div class="error" ng-show="paymentForm.amount.$error.positive">Amount should be positive number.</div>
</div>

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

Comments

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.