验证ngfor中的输入

时间:2019-08-08 12:10:19

标签: angular forms validation

在下面找到的HTML格式包含一个名为“ caseName”的输入字段和任意多个名为“ exhibitName”的输入字段。通过单击“添加新展览”按钮,会将新展览添加到“ newCaseExhibits”中,从而在表单中添加新的输入字段。

<form #newCaseForm="ngForm">
    <div id="newCaseMenu">
        <div id="newCaseHeader">
            <b>New Case</b>
        </div>
        <div id="newCaseInnerContainer">

            <div class="attrValueContainer">
                <span class="attr-name">Name:</span>
                <input class="attr-value edit" type="text" name="name" 
                 required [(ngModel)]="newCase.name" #caseName="ngModel"/>   
            </div>
            <div *ngIf="(caseName.invalid || nameAlreadyInUse(caseName.model) ) && (caseName.dirty || caseName.touched)" 
             class="attrValueContainer">
                <span class="attr-name"></span>
                <div *ngIf="caseName.invalid">
                    A case name is required.
                </div>
                <div *ngIf="nameAlreadyInUse(caseName.model)">
                   This case name already exists.
                </div>
            </div>

            <div *ngFor="let exhibit of newCaseExhibits; let i = index" >
                <div class="exhibitContainer">
                    <span class="attr-name">Exhibit:</span>
                    <input class="attr-value" type="text" [(ngModel)]="exhibit.name" 
                     required name="{{i}}exhibit" #exhibitName="ngModel">
                </div>

                <div *ngIf="(exhibitName.invalid || exhibitNameAlreadyInUse(exhibitName.model) ) && (exhibitName.dirty || exhibitName.touched))" 
                 class="attrValueContainer">
                    <span class="attr-name"></span>
                    <div *ngIf="exhibitName.invalid">
                        A name is required                    
                    </div>
                    <div *ngIf="exhibitNameAlreadyInUse(exhibitName.model)">
                        There is already another exhibit with this name.
                    </div>
                </div>
            </div>

            <div class="button extraMarginTop" (click)="onBtnAddExhibitToNewCaseClicked()">
                Add new exhibit
            </div><br>
            <button class="bottomRight" 
             [class.disabled]="newCaseForm.invalid || nameAlreadyInUse(caseName.model)"
             [disabled]="newCaseForm.invalid || nameAlreadyInUse(caseName.model)"
             (click)="onBtnCreateNewCaseClicked()">
                Create case
            </button>
        </div>
    </div>
</form>

现在,每个展览品的输入字段都将单独进行验证。但是,如何在“创建案例”按钮上检查此验证状态,以使用户无法使用无效的展览名称创建案例?

0 个答案:

没有答案