Angular의 양식 유효성 검사
20239 단어 angulartypescript
오늘 저는 제가 찾은 Angular에서 유효성 검사를 작성하는 가장 좋은 방법을 설명하겠습니다. 여기서 목표는 시간을 절약하고 깨끗하고 읽기 쉬운 코드를 갖는 것입니다.
1- 모듈에 FormsModule 및 ReactiveFormsModule을 추가합니다.
FormsModule
및 ReactiveFormsModule
를 가져와 imports 배열에 추가합니다.import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
///.... the rest or your modules
FormsModule,
ReactiveFormsModule,
],
bootstrap: [AppComponent]
})
export class AppModule { }
2- 코드 작성
우리의 목표는 다음 양식을 만드는 것이므로 여기서는
Tailwind
를 사용하겠습니다.1-에서
form.component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators,FormBuilder} from '@angular/forms';
@Component({
selector: 'app-form',
templateUrl: './form.component.html'
})
export class FormComponent implements OnInit {
constructor() { }
// you can add initial values if you are updating something
formgroup = new FormBuilder().group({
email: new FormControl('initial value here', [Validators.minLength(2),Validators.required,Validators.email]),
password: new FormControl('', [Validators.required]),
checkPassword: new FormControl('', [Validators.required]),
}, { validator: this.match('password','checkPassword') }
);
/*
This function will return a Boolean value.
If you want to check whether the input
has any error, pass the input name as first parameter.
And
if it has a specific error, pass the input name as first
parameter and the error name as the second parameter
*/
hasError(InputName: string,error?:'maxlength'|'minlength'|'required'|'email'|'confirmed'|'max'|'min'|'pattern'):boolean {
if(error){
return this.formgroup.get(InputName)?.hasError(error) &&
(this.formgroup.get(InputName)?.dirty || this.formgroup.get(InputName)?.touched)?true:false
}else{
return this.formgroup.get(InputName)?.invalid &&
(this.formgroup.get(InputName)?.dirty || this.formgroup.get(InputName)?.touched)?true:false
}
}
// usually I Put this function in separate ts file
// I create helpers folder in src/helpers then create files for
//the functions that I use too much in my project
match(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors['confirmed']) {
return;
}
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ confirmed: true });
} else {
matchingControl.setErrors(null);
}
};
}
// this function won't trigger unless the form is valid
// we'll see how in the form.component.html
onSubmit(input: any): void {
console.log(input)
}
ngOnInit(): void {
}
}
2-에서
form.component.html
<form
[formGroup]="formgroup"
(ngSubmit)="onSubmit(formgroup.value)"
class="w-6/12 mx-auto"
>
<p class="mb-4"></p>
<div class="mb-4">
<!--Add formControlName for each input -->
<!-- If you want to apply different styles on errors all
what you need to do is to use the hasError() function -->
<input
type="text"
formControlName="email"
class="form-control block w-full px-3 py-1.5 text-base font-normal
text-gray-700 bg-white bg-clip-padding border border-solid
rounded m-0 focus:text-gray-700 focus:bg-white focus:outline-none"
[ngClass]="
hasError('email')
? 'border-red-300 focus:border-red-600'
: 'border-gray-300 focus:border-blue-600'
"
placeholder="email"
/>
<!-- hasError() function takes two parameters the first one is
formControlName and the second is error type.
you need to know if you don't add the second parameter, it'll
return if the input has any errors or not. -->
<div
class="m-1 text-red-500 capitalize"
*ngIf="hasError('email', 'required')"
>
Please enter email
</div>
<div
class="m-1 text-red-500 capitalize"
*ngIf="hasError('email', 'email')"
>
Please enter valid email
</div>
</div>
<div class="mb-4">
<input
type="text"
formControlName="password"
class="form-control block w-full px-3 py-1.5 text-base font-normal text-gray-700
bg-white bg-clip-padding border border-solid rounded m-0 focus:text-gray-700
focus:bg-white focus:outline-none"
[ngClass]="
hasError('password')
? 'border-red-300 focus:border-red-600'
: 'border-gray-300 focus:border-blue-600'
"
placeholder="password"
/>
<div
class="m-1 text-red-500 capitalize"
*ngIf="hasError('password', 'required')"
>
Please enter password
</div>
</div>
<div class="mb-4">
<input
type="text"
formControlName="checkPassword"
class="form-control block w-full px-3 py-1.5 text-base font-normal
text-gray-700 bg-white bg-clip-padding border border-solid
rounded m-0 focus:text-gray-700 focus:bg-white focus:outline-none"
[ngClass]="
hasError('checkPassword')
? 'border-red-300 focus:border-red-600'
: 'border-gray-300 focus:border-blue-600'
"
placeholder="checkPassword"
/>
<div
class="m-1 text-red-500 capitalize"
*ngIf="hasError('checkPassword', 'required')"
>
Please enter checkPassword
</div>
<div
class="m-1 text-red-500 capitalize"
*ngIf="hasError('checkPassword', 'confirmed')"
>
The two passwords do not match
</div>
</div>
<div class="text-center pt-1 mb-12 pb-1">
<!-- here we should add [disabled]="formgroup.invalid"
to make sure that the user won't be able to submit unless
the form is valid, also it's useful in testing making it easier -->
<button
[disabled]="formgroup.invalid"
class="main-color inline-block px-6 py-2.5 text-white font-medium text-xs leading-tight uppercase
rounded shadow-md hover:bg-blue-700 hover:shadow-lg focus:shadow-lg focus:outline-none focus:ring-0
active:shadow-lg transition duration-150 ease-in-out w-full mb-3"
type="submit"
>
Submit
</button>
</div>
</form>
페이지는 다음과 같아야 합니다.
🥳🥳🥳 축하합니다.
Reference
이 문제에 관하여(Angular의 양식 유효성 검사), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/chrollo4ki/form-validation-in-angular-25o7텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)