字段的角度验证有效但不是必需的

时间:2015-05-27 13:20:57

标签: regex angularjs validation

我的模板中有以下内容:

<div class="form-group">
    <label for="work_phone">Work Phone</label>
    <input type="text"
        class="form-control"
        name="workPhone"
        ng-class="{'borderRed': contactInformation.workPhone.$invalid  && contactInformation.submitted}"
        ng-model="controller.contactInformation.workPhone"
        ng-pattern="/^\d+$/"
        maxlength="10"
        id="work_phone">

    <small class="error"
        ng-show="contactInformation.workPhone.$invalid && !contactInformation.workPhone.$pristine && contactInformation.submitted">
            That's not a valid phone number (only numerics are allowed)!
    </small>
</div>

条件:
1。如果字段为空白/未触及,则表单应保持有效 2. 如果字段中有任何值,则应根据ng-pattern中提供的正则表达式对其进行验证。

看起来很琐碎。我知道。但出于某些愚蠢的原因,无法找到解决方案

3 个答案:

答案 0 :(得分:0)

因此,如果我理解你想要的问题只允许使用数字,你可以使用这个指令阻止所有其他字符:

    .directive('onlyDigits', function () {
return {
    require: 'ngModel',
    restrict: 'A',
    link: function (scope, element, attr, ctrl) {
        function inputValue(val) {
            if (val) {
                var digits = val.replace(/[^0-9]/g, '');

                if (digits !== val) {
                    ctrl.$setViewValue(digits);
                    ctrl.$render();
                }
                return parseInt(digits,10);
            }
            return undefined;
        }            
        ctrl.$parsers.push(inputValue);
    }
};

});

并将指令添加到您的输入中,速度更快,您也无法使用ng-pattern:

                    <input type="text"
                           class="form-control"
                           name="workPhone"
                           maxlength="10"
                           id="work_phone" onlyDigits>

答案 1 :(得分:0)

您的表单目前仍然有效,因为您正在检查<?php $where = [ 'is_deleted' => 0, 'is_hidden' => 0, 'battle_type' => 'public', ]; $postdata = new postdataModel; $processes = new processesModel; $command = $postdata->getDbConnection()->createCommand() ->select('t.id, t.title, t.date_created, t.video_id, t.audio_id, t.created_by, t.updated, t.gamenumber, t.cat_id, t.is_deleted, t.marked_by, t.is_hidden, t.battle_type, t.media') ->from('postdata AS t') ->leftJoin('processes AS pv', 'pv.video_id = t.video_id AND pv.status = 3') ->where('cat_id IS NOT NULL AND is_deleted = :is_deleted AND is_hidden = :is_hidden AND battle_type = :battle_type') ->order('t.date_created DESC') ; $data = $command->queryAll(); 。当表单为空时尝试使用$pristine来重置它,因此不再获得$setPristine()类。

答案 2 :(得分:0)

您可以更改正则表达式,以便它允许空字符串:

ng-pattern="/^\d*$/"