表单验证不适用于角度js

时间:2017-06-16 04:40:11

标签: angularjs

我有以下内容:

<form name="ctrl.form" class="form-horizontal" ng-class="{true: 'has-error'}[submitted && form.email.$invalid]"
      novalidate>

    <div class="form-group" ng-class="{'has-error' : ctrl.form.inputName.$dirty && ctrl.form.inputName.$invalid}">
        <label for="inputName" class="col-sm-2 control-label">Name</label>
        <div class="col-sm-8">
            <input type="text" class="form-control" id="inputName" name="inputName" ng-model="ctrl.app.name"
                   placeholder="Enter stack name" ng-disabled="ctrl.editMode" ng-required='true'
                   ng-minlength='3' ng-maxlength='32' required/>
        </div>
        <span ng-show="ctrl.form.inputName.$error.required && !ctrl.form.inputName.$pristine" class="help-block">Name is required</span>
        <span ng-show="ctrl.form.inputName.$error.minlength" class="help-block">Name is too short</span>
        <span ng-show="ctrl.form.inputName.$error.maxlength" class="help-block">Name is too long</span>
        <span ng-show="ctrl.form.inputName.$error.pattern" class="help-block">Name has invalid characters</span>
    </div>


    <div class="form-group" ng-class="{'has-error' : ctrl.hasServerErrors}">
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-primary" ng-disabled="ctrl.isCreating"
                    ng-click="ctrl.SubmitForm()">{{ctrl.editMode ? 'Update' :
                ctrl.isCreating? 'Creating': 'Create'}}
            </button>
            <span ng-show="ctrl.hasServerErrors" class="help-block"
                  ng-repeat="serverError in ctrl.serverErrors">
            {{serverError}}
        </span>
        </div>
    </div>
    <div class="alert alert-success" ng-show="ctrl.showUpdateSuccessAlert">
        <strong>Successfully updated!</strong>
    </div>
</form>

现在,问题是,即使我已将required tag添加到名称,仍然在我单击提交按钮时,调用将转到后端服务,而不显示该名称是必需的并且必须提供。

我错过了什么?谢谢!

2 个答案:

答案 0 :(得分:0)

<div class="" ng-show="ctrl.form.inputName.$dirty && ctrl.form.inputName.$invalid">
Message which you want to print.
</div>

添加此内容。

希望这会对你有所帮助。

答案 1 :(得分:0)

在提交表单之前,您应该检查表单是否有效。

<button type="submit" class="btn btn-primary" ng-disabled="ctrl.form.$invalid"
                ng-click="ctrl.SubmitForm()">{{ctrl.editMode ? 'Update' :
            ctrl.isCreating? 'Creating': 'Create'}}
        </button>
当表单无效时,

$ invalid将为true。