Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

validation - angular validate input type="number"

I have markup like this:

<form name="myForm" ng-controller="myCtrl" novalidate>
    <input ng-model="theValue" type="range" min="0" max="100" required>
    <input ng-model="theValue" type="number" required></input>
    <span ng-show="theValue.$error.number">Hey! No letters, buddy!</span>
</form>

And I want the span to show when the user accidentally types a letter in the second input. Simple, right? As an (probably) related problem, the value in the second input disappears when the user moves the first slider input. Why? This doesn't happen if I remove type-number from the markup.

To be clear: I want the user to see the tooltip error immediately when it's typed, without any "submit" action. (I'd prefer not to have to use the form element at all in fact, but all the related demos seem to require it.)

http://jsfiddle.net/7FfWT/

Any workaround is most welcome. Please post a working fiddle if possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There seems to be a weird issue with type="number" playing nicely with other inputs.

The posts in this google groups post should get you on the right track. In particularly, the last post there: https://groups.google.com/forum/#!msg/angular/Ecjx2fo8Qvk/x6iNlZrO_mwJ

The jsfiddle link is: http://jsfiddle.net/ABE8U/

As a work around, he's made a directive:

.directive('toNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            ctrl.$parsers.push(function (value) {
                return parseFloat(value || '');
            });
        }
    };
});

Credit to Schmuli Raskin


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...