AngularJS在提交时显示错误

时间:2016-11-11 19:26:50

标签: angularjs

我正在使用AngularJS步骤向导并在表单内部进行第一步,当用户尝试点击提交时,我需要出现验证错误。现在我有以下内容:

<span class="error" ng-show="user.validate.step1.firstname.$invalid">Required Field</span>

但错误显示当我第一次转到该步骤时,当我开始在该字段中输入时它会消失,我希望当用户尝试点击提交时出现,而不是在他们第一次转到步骤时。我已经有了这个来表示必填字段

<span class="error">*</span>

以下是完整代码:

<form name="user.validate.step1" novalidate>
                <div class="container">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="firstname" class="col-md-4 form-label">First Name:</label>
                                <div class="col-md-8">
                                    <div class="input-group">
                                        <input class="form-control" type="text" name="firstname" ng-model="user.firstname" value="{{user.firstname}}" ng-blur="blur1=true" required />
                                        <span class="error" ng-show="user.validate.step1.firstname.$invalid">*</span>
                                    </div>
                                </div>
                            </div>
</div>
</div>
</div>
</form>

请记住,我在此表单中有多个输入。

2 个答案:

答案 0 :(得分:0)

使用ng-click="validateInputs()"在按钮中添加验证,并创建var invalidEntry和函数validateInputs()以检查输入是否有效。像这样:

var inputs = [inputModel1,inputModel2,inputModel3];

function validateInputs(){
    invalidEntry = false;
    for(e in inputs){
        if(CheckInvalid(inputs[e])){
            invalidEntry = true;
            return;
        }
    }

}

function CheckValid(string){
    if(string == "" || string === null || string === undefined){
        return true;
    } else {
        return false;
    }
}

提交按钮:

<button ng-click="validateInputs()">Submit</button>

跨度:

<span class="error" ng-show="invalidEntry">Required Field</span>

输入应如下所示:

<input type="text" ng-model="inputModel1"></input>
<input type="text" ng-model="inputModel2"></input>
<input type="text" ng-model="inputModel3"></input>

答案 1 :(得分:0)

您应该按以下方式更改ngShow

CREATE TABLE tbl_animal
(
    id INT identity(1, 1) NOT NULL, 
    name VARCHAR (150) NOT NULL
) ;

set identity_insert tbl_animal on 
INSERT INTO tbl_animal (id, name) VALUES (111, 'dog');
INSERT INTO tbl_animal (id, name) VALUES (222, 'bird');
set identity_insert tbl_animal off

dbcc CHECKIDENT('tbl_animal', RESEED, 222) --you really do want 222 here so the next inserted identity will be 223

INSERT INTO tbl_animal (name) VALUES ('fish')

select * from tbl_animal

查看此文章栏AngularJS Form Validation: Only Showing Errors After Submitting the Form