확인란을 선택해야 함
FormBuilder for Angular를 사용하여 확인란을 선택할 때까지 단추를 사용하지 않습니다.확인란의 값을 명시적으로 확인하고 싶지 않으며 단순히 확인할 수 있도록 검증기를 사용하는 것을 선호합니다.form.valid
.
아래의 두 검증 사례에서 확인란은 다음과 같습니다.
interface ValidationResult {
[key:string]:boolean;
}
export class CheckboxValidator {
static checked(control:Control) {
return { "checked": control.value };
}
}
@Component({
selector: 'my-form',
directives: [FORM_DIRECTIVES],
template: ` <form [ngFormModel]="form" (ngSubmit)="onSubmit(form.value)">
<input type="checkbox" id="cb" ngControl="cb">
<button type="submit" [disabled]="!form.valid">
</form>`
})
export class SomeForm {
regForm: ControlGroup;
constructor(fb: FormBuilder) {
this.form = fb.group({
cb: [ CheckboxValidator.checked ]
//cb: [ false, Validators.required ] <-- I have also tried this
});
}
onSubmit(value: any) {
console.log('Submitted: ', this.form);
}
}
Angular 2.3.1 이후에는 다음을 사용할 수 있습니다.
구성 요소:
this.formGroup = this.formBuilder.group({
cb: [false, Validators.requiredTrue]
});
템플릿:
<form [formGroup]="formGroup">
<label><input type="checkbox" formControlName="cb"> Accept it</label>
<div style="color: red; padding-top: 0.2rem" *ngIf="formGroup.hasError('required', 'cb')">
Required
</div>
<hr>
<div>
<button type="submit" [disabled]="formGroup.invalid">Submit</button>
</div>
</form>
Validator 패턴을 사용하여 올바른(부울) 값을 확인할 수 있습니다.
<input type="checkbox" [formControl]="myForm.controls['isTosRead']">
그리고 다음은 구속력입니다.
this.myForm = builder.group({
isTosRead: [false, Validators.pattern('true')]
});
<h1>LOGIN</h1>
<form [formGroup]="signUpForm">
<input type="checkbox" formControlName="cb">
<button type="submit" [disabled]="!loginForm.valid" (click)="doLogin()">Log in</button>
</form>
export class Login {
public signUpForm: FormGroup;
constructor(fb: FormBuilder) {
this.signUpForm = fb.group({
cb: [false, Validators.requiredTrue]
});
}
doLogin() {
}
}
.ts
@Component({
selector: 'my-app',
template: `
<h1>LOGIN</h1>
<form [ngFormModel]="loginForm" #fm="ngForm" (submit)="doLogin($event)">
<input type="checkbox" id="cb" ngControl="cb" #cb="ngForm" required>
<button type="submit" [disabled]="!loginForm.valid">Log in</button>
<br/>
<div>Valid ={{cb.valid}}</div>
<div>Pristine ={{cb.pristine}}</div>
<div>Touch ={{cb.touched}}</div>
<div>form.valid?={{loginForm.valid}}</div>
<BR/>
<BR/>
</form>
`,
directives: [ROUTER_DIRECTIVES,FORM_DIRECTIVES,CORE_DIRECTIVES]
})
export class Login {
constructor(fb: FormBuilder) {
this.loginForm = fb.group({
cb: [false, Validators.required],
//cb: ['',Validators.required] - this will also work.
});
}
doLogin(event) {
console.log(this.loginForm);
event.preventDefault();
}
}
작업용 플런커.
변경 사항이 있으면 알려주시기 바랍니다.
확인란에 대해 Validator.required가 제대로 작동하지 않습니다.확인란을 선택한 다음 선택을 취소하면 FormControl이 선택되지 않은 경우에도 유효한 것으로 표시됩니다.그것은 사실이든 거짓이든 당신이 그것을 어떤 것으로 설정했는지만 확인한다고 생각합니다.
다음은 FormControl에 추가할 수 있는 빠르고 간단한 검증자입니다.
mustBeChecked(control: FormControl): {[key: string]: string} {
if (!control.value) {
return {mustBeCheckedError: 'Must be checked'};
} else {
return null;
}
}
HTML 양식
<div class="col-md-12">
<div class="form-group">
<input type="checkbox" class="form-check-input" id="agree" formControlName="agree">
<label class="form-check-label" for="agree">
I agree to our <a target="_blank" href="#">Terms of use</a> and
<a target="_blank" href="#">Privacy Policy</a>.
</label>
<div class="text-danger" *ngIf="(isRegSubmit||regForm.get('agree').touched) &&
regForm.get('agree').hasError('required')">
Please agree to terms of use and privacy policy.
</div>
</div>
</div>
TS 파일
regForm: FormGroup;isRegSubmit: boolean = false;
constructor(
private fb: FormBuilder
}
this.regForm = this.fb.group({
agree : [false, Validators.requiredTrue]
});
Validators.required not worked 또한 값을 확인하여 오류 메시지를 표시하고 사용자의 제출을 제한할 수 있지만 유효성 검사를 사용하지 않기 때문에 좋은 접근 방식이 아닙니다. 따라서 확인란이 하나만 있을 때마다 Validators.requiredTrue를 추가합니다.
다음과 같은 간단한 예가 있습니다.
구성 요소:
login : FormGroup;
constructor(@Inject(FormBuilder)formBuilder : FormBuilder) {
this.login = formBuilder.group({userName: [null], password: [null],
staySignedIn: [false,Validators.pattern('true')]});
}
HTML에서:
<form [formGroup]="login" (ngSubmit)="onSubmit()">
<div class="form-group">
<input formControlName="userName" required>
</div>
<div class="form-group">
<input formControlName="password" type="password" required>
</div>
<div>
<label>
<input formControlName="staySignedIn" checked="staySignedIn" type="checkbox"> bla
</label>
</div>
<button type="submit">bla</button>
<div >
<a href>bla?</a>
</div>
</form>
Angular 8의 경우, 3개의 체크박스 중 적어도 1개의 체크박스가 선택되었는지 확인하기 위해 아래와 같이 했습니다.
form = new FormGroup({
// ...more form controls...
myCheckboxGroup: new FormGroup({
myCheckbox1: new FormControl(false),
myCheckbox2: new FormControl(false),
myCheckbox3: new FormControl(false),
}, requireCheckboxesToBeCheckedValidator()),
// ...more form controls...
});
사용자 지정 검증자 생성
import { FormGroup, ValidatorFn } from '@angular/forms';
export function requireCheckboxesToBeCheckedValidator(minRequired = 1): ValidatorFn {
return function validate (formGroup: FormGroup) {
let checked = 0;
Object.keys(formGroup.controls).forEach(key => {
const control = formGroup.controls[key];
if (control.value === true) {
checked ++;
}
});
if (checked < minRequired) {
return {
requireCheckboxesToBeChecked: true,
};
}
return null;
};
}
그리고 html에서 아래와 같이 사용했습니다.
<ng-container [formGroup]="form">
<!-- ...more form controls... -->
<div class="form-group" formGroupName="myCheckboxGroup">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" formControlName="myCheckbox1" id="myCheckbox1">
<label class="custom-control-label" for="myCheckbox1">Check</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" formControlName="myCheckbox2" id="myCheckbox2">
<label class="custom-control-label" for="myCheckbox2">At least</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" formControlName="myCheckbox3" id="myCheckbox3">
<label class="custom-control-label" for="myCheckbox3">One</label>
</div>
<div class="invalid-feedback" *ngIf="form.controls['myCheckboxGroup'].errors && form.controls['myCheckboxGroup'].errors.requireCheckboxesToBeChecked">At least one checkbox is required to check</div>
</div>
<!-- ...more form controls... -->
</ng-container>
PrimeNG를 사용하는 경우 다음과 같은 TAG app-form-required-field를 통해 이 작업을 수행할 수 있습니다.
<p-checkbox name="_yes" #active="ngModel" required value="true"
label="Active" binary="true" [(ngModel)]="filter._yes"></p-checkbox>
<p-checkbox name="_no" #inactive="ngModel" required label="Inactive"
binary="true" [(ngModel)]="filter._no"></p-checkbox>
<app-form-required-field
*ngIf="!filter._yes && !filter._no"
[form]="active"
[form]="inactive"
id="msgAtivo"
requiredMessage="Field required!"
>
</app-form-required-field>
아래의 조건에 검증자 단순 검사를 넣었음에도 불구하고.
@Component({
selector: 'my-form',
directives: [FORM_DIRECTIVES],
template: ` <form [ngFormModel]="form" (ngSubmit)="onSubmit(form.value)">
<input type="checkbox" id="cb" ngControl="cb">
<button type="submit" [disabled]="!form.valid && !cb.value">
</form>`
})
구성 요소:
import { FormGroup, FormBuilder, Validators, AbstractControl } from '@angular/forms';
public profileForm!: FormGroup;
constructor(
private _fb: FormBuilder
) { }
ngOnInit(): void {
this._createForm();
this._setValidationRule();
}
get fc(): { [key: string]: AbstractControl } {
return this.profileForm.controls;
}
private _createForm() {
const self = this;
self.profileForm = self._fb.group({
required_checkbox: [false],
zipcode: [''],
city: [''],
town: [''],
});
}
private _setValidationRule() {
const self = this;
self.profileForm.get('required_checkbox').valueChanges.subscribe(
ruleStatus => {
if (ruleStatus) {
self.profileForm.get('zipcode').setValidators(Validators.required);
self.profileForm.get('city').setValidators(Validators.required);
self.profileForm.get('town').setValidators(Validators.required);
} else {
self.profileForm.get('zipcode').setValidators(null);
self.profileForm.get('city').setValidators(null);
self.profileForm.get('town').setValidators(null);
}
self.profileForm.get('zipcode').updateValueAndValidity();
self.profileForm.get('city').updateValueAndValidity();
self.profileForm.get('town').updateValueAndValidity();
});
}
템플릿
<mat-checkbox class="terms" formControlName="required_checkbox">Pickup Riraku</mat-checkbox>
<mat-form-field appearance="outline">
<mat-label>Zip Code</mat-label>
<input matInput type="text" formControlName="zipcode" placeholder="">
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>City</mat-label>
<input matInput type="text" formControlName="city" placeholder="">
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Town</mat-label>
<input matInput type="text" formControlName="town" placeholder="">
</mat-form-field>
확인란에 값을 설정하려면 확인란 자체에 값이 있는지 여부를 지정할 수 있습니다.테스트할 수 있습니다.Validators.required
선택한 경우 값을 전달하거나 true를 전달하고 선택하지 않은 경우 null을 전달하거나 false를 전달합니다.그리고 ChangeInput에서 메서드를 트리거합니다. <input type="method" (변경)="changeInput($event)">
public changeInput(event): void {
this.isChecked = event.target.checked;
// passing the value
this.onChange(this.isChecked ? (this.value ? this.value : true) : false);
// set touched
if (!this.isTouched) {
this.isTouched = true;
this.onTouch();
}
}
변경 사항을 탐지하는 메서드 만들기
checkValue(event: any) {
this.formulario.patchValue({
checkboxControlName: event.target.checked
})
}
이벤트 변경에 해당 방법을 적용하고,ngModel required
특성.
<input (change)="checkValue($event)" type="checkbox" formControlName="checkboxControlName" value="true" ngModel required>
그리고 전통적인 방법을 사용하여 검증합니다.
this.formulario = new FormGroup({
checkboxControlName: new FormControl('', [Validators.required])
});
언급URL : https://stackoverflow.com/questions/35462316/requiring-a-checkbox-to-be-checked
'programing' 카테고리의 다른 글
com.google.android.gms.maps에 대한 다른 조각으로 ID, 태그 null 또는 상위 ID가 중복됩니다.지도 조각 (0) | 2023.08.15 |
---|---|
도커를 사용하여 포트를 두 개 이상 노출하려면 어떻게 해야 합니까? (0) | 2023.08.15 |
C x86의 64비트 루프 성능 (0) | 2023.08.15 |
도커 파일에서 도커 인스턴스를 실행하려면 어떻게 해야 합니까? (0) | 2023.08.15 |
C++에서 C 코드를 사용하는 방법 (0) | 2023.08.15 |