如何自定义角度数输入验证

时间:2015-04-23 18:05:21

标签: angularjs

我正在使用一个验证数字输入框的指令。我想改变它以满足我的需要。现在,它允许我输入数字或文本,并在按钮单击时抛出错误消息。它还会触发该功能。我想在输入文本时立即抛出错误信息,我也希望在两个输入都有效之前禁用该按钮。

总结一下,我需要在输入的任何文本上立即触发错误消息。并且需要禁用该按钮,直到两个字段都有效

<form class="form-horizontal">
        <div class="form-group">
            <div class="col-md-12">
                <label for="inputEmail3" class="control-label">Price</label>
                <input class="form-control input-sm" to-number id="Price" type="number" ng-model="customSubjectProperty.price" ng-pattern=" /^\d+$/" placeholder="Price">
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-12">
                <label class="control-label">Sqft</label>
                <input class="form-control input-sm" to-number id="Sqft" type="number" ng-model="customSubjectProperty.sqft" ng-keypress="chartController.newInputKeyPress()" ng-pattern="/^\d+$/" placeholder="Sqft">
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-12" style="margin-top:12px">
                <button class="btn btn-primary btn-block btn-sm" ng-click="chartController.addSubjectPoint(customSubjectProperty)" ng-enter="chartController.addSubjectPoint(customSubjectProperty)">Add Point</button>
            </div>
        </div>
    </form>

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

});

1 个答案:

答案 0 :(得分:1)

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