Angular 2 - 如果选中复选框,则必填字段验证

时间:2016-07-29 08:49:03

标签: validation checkbox angular

Hy们我是Angular2的新手,也是JS框架的新手。我在官方网站上流动教程,并且无法找到解决此问题的方法。

所以我有一个可选的复选框,但是如果复选框是"选中"显示一个新的输入字段。这部分不是问题。问题是我使用基于模态的验证,只有选中复选框,我才能弄清楚如何使这个新输入字段成为必需。

到目前为止,这可能是实施:

<form [formGroup]="form" (ngSubmit)="onSubmit()">

<!--{{form}}-->

<div formGroupName="test">
    <div class="field">
        <div class="checkbox">
            <input type="checkbox" name="entryRecurring" value="" id="entryRecurring" formControlName="entryRecurring" />
            <label for="entryRecurring">
                <div class="checkbox_icon"></div>
                Recurring Entry
            </label>
        </div>
    </div>

    <div *ngIf="form.value.test.entryRecurring">
        <div class="field">
            <label for="entryRecurringAmount">Repeat Amount</label>
            <input type="text" name="entryRecurringAmount" value="" id="entryRecurringAmount" formControlName="entryRecurringAmount" />
        </div>
    </div>
</div>

<div class="field last">
    <button name="submit" id="submit" class="btn btn_sushi"  [disabled]="!form.valid">Submit</button>
</div>

    import {Component, Input, OnInit, OnChanges} from '@angular/core';
    import { Validators } from '@angular/common';
    import { REACTIVE_FORM_DIRECTIVES, FormGroup, FormControl, FormBuilder } from '@angular/forms';  
    import { FormMessages } from './../helpers/formMessages.component';
    import {EntriesService} from './entries.service';    
    import {ValidationService} from '../helpers/validation.service';
    import {Category, CategoryByType} from '../../mock/mock-categories';


    @Component({
        selector: 'entryForm',
        templateUrl: 'app/components/entries/entriesEdit.template.html',
        directives: [REACTIVE_FORM_DIRECTIVES, FormMessages],
        providers: [EntriesService, ValidationService]

    })
    export class EntriesEditComponent implements OnInit, OnChanges {
        @Input() control: FormControl;
        public form:FormGroup;
        public submitted:boolean = false;
        // private selectedId: number;

        categories: Category[];
        categoriesSortedByType: CategoryByType[];

        constructor(
            private _fb:FormBuilder,
            private _entriesService: EntriesService
            // private _router: Router
        ) {

            this.form = this._fb.group({

                test: this._fb.group({
                    entryRecurring: [''],
                    entryRecurringAmount: [''],
                })
            });
        }
onSubmit() {
        this.submitted = true;
        // console.log(this.form.value);

        if (this.form.dirty && this.form.valid) {
            this._entriesService.saveEntry(this.form.value);
        }
    }

1 个答案:

答案 0 :(得分:0)

您可以使用自定义验证服务来完成此操作。

import {NgFormModel} from "angular2/common";
import {Component, Host} from 'angular2/core';

@Component({
    selector : 'validation-message',
    template : `
        <span *ngIf="errorMessage !== null">{{errorMessage}}</span>
    `,
    inputs: ['controlName : field'],
})



export class ControlMessages {

    controlName : string;

    constructor(@Host() private _formDir : NgFormModel){

    }

    get errorMessage() : string {
        let input = this._formDir.form.find(this.controlName);
        let checkBx = this._formDir.form.find('checkBoxName');
        if(input.value.trim() === '' && checkBx.checked) {
                return 'The input field is now required'
        }
       return null;
    }

}

然后使用像bellow

这样的新组件
 <div *ngIf="form.value.test.entryRecurring">
        <div class="field">
            <label for="entryRecurringAmount">Repeat Amount</label>
            <input type="text" name="entryRecurringAmount" value="" id="entryRecurringAmount" ngControl="entryRecurringAmount" />
            <validation-message field="entryRecurringAmount"></validation-message>
        </div>
    </div>

希望有所帮助!

相关问题