表单验证错误,输入字段应突出显示错误

时间:2018-04-17 06:41:28

标签: angularjs angular-forms

我有以下HTML代码,如果我的字段输入了一些值并被删除,我会用红色突出显示我的字段并收到错误消息,需要手机号码。但是,如果我键入字母,我收到错误消息,只有数字,但输入框不会突出显示为红色。

HTML:

<div class="form-group" ng-class="{ 'has-error': ((submitted || cform.ccode1.$dirty || cform.submitted) && cform.ccode1.$invalid) || ((submitted || cform.mobile1.$dirty || cform.submitted) && cform.mobile1.$invalid) }" class="help-block">

    <div class="input-group">
        <div class="input-group-addon" style="width:25%;">
            <input type="text" class="form-control" maxlength="5" placeholder="Code" ng-model="model.ccode1" name="ccode1" ng-pattern="/^[0-9]*$/"
                readdonly required>

        </div>

        <input type="text" class="form-control" placeholder="Mobile" name="mobile1" ng-model="model.mobile1" ng-pattern="/^[0-9]*$/"
            min-length="2 " required>

    </div>
    <span ng-show="cform.ccode1.$dirty && cform.ccode1.$error.required" class="help-block">Code is required</span>
    <span ng-show="cform.mobile1.$dirty && cform.mobile1.$error.required" class="help-block1">Mobile number is required</span>
    <span ng-show="cform.ccode1.$dirty && cform.ccode1.$error.pattern" class="help-block">
        Must contain only numbers </span>
    <span ng-show="cform.mobile1.$dirty && cform.mobile1.$error.pattern" class="help-block1">
        Must contain only numbers </span>

</div>

when field is empty and cleared

when alphabet entered

1 个答案:

答案 0 :(得分:0)

也许您可以将指令设为仅包含以下数字:

app.directive('uiNumber', [function() {
return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModelCtrl, $filter, $parse) {
        element.mask("99999");

          }
       }
 }]);
<input type="text" class="form-control" placeholder="Mobile" name="mobile1" ng-model="model.mobile1" ng-pattern="/^[0-9]*$/"
        min-length="2 " required ui-number>

您只需要将 mask.js 添加到您的项目中:http://bguzmanrio.github.io/maskjs/

希望这个帮助