HOHO - <KIOSK> 유효성 검사 예

chan_hari·2024년 7월 29일

HOHO-DIARY

목록 보기
45/56
post-thumbnail

1. 이메일 유효성 검사 예시:

이 예시는 사용자가 이메일 주소를 입력하는 양식을 구현합니다. 이메일 필드는 필수 필드이며, 올바른 이메일 형식을 가져야 합니다. 유효하지 않은 이메일 형식이 입력되면 사용자에게 오류 메시지가 표시됩니다.

htmlCopy code
<form [formGroup]="emailForm" (ngSubmit)="onSubmit()">
  <input type="email" formControlName="email">
  <div *ngIf="emailForm.get('email').invalid && emailForm.get('email').touched">
    <div *ngIf="emailForm.get('email').errors.required">Email is required.</div>
    <div *ngIf="emailForm.get('email').errors.email">Invalid email format.</div>
  </div>
  <button type="submit" [disabled]="emailForm.invalid">Submit</button>
</form>
typescriptCopy code
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-email-form',
  templateUrl: './email-form.component.html',
  styleUrls: ['./email-form.component.css']
})
export class EmailFormComponent {
  emailForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.emailForm = this.formBuilder.group({
      email: ['', [Validators.required, Validators.email]]
    });
  }

  onSubmit() {
    if (this.emailForm.valid) {
      // 폼 제출 시 수행할 로직 작성
    }
  }
}

1. 비밀번호 확인 예시:

이 예시는 사용자가 비밀번호와 비밀번호 확인을 입력하는 양식을 구현합니다. 비밀번호는 최소 8자 이상이어야 하며, 비밀번호 확인 필드는 비밀번호와 일치해야 합니다.

htmlCopy code
<form [formGroup]="passwordForm" (ngSubmit)="onSubmit()">
  <input type="password" formControlName="password" placeholder="Password">
  <input type="password" formControlName="confirmPassword" placeholder="Confirm Password">
  <div *ngIf="passwordForm.hasError('passwordsNotMatch') && passwordForm.get('confirmPassword').touched">
    Passwords do not match.
  </div>
  <button type="submit" [disabled]="passwordForm.invalid">Submit</button>
</form>
typescriptCopy code
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-password-form',
  templateUrl: './password-form.component.html',
  styleUrls: ['./password-form.component.css']
})
export class PasswordFormComponent {
  passwordForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.passwordForm = this.formBuilder.group({
      password: ['', [Validators.required, Validators.minLength(8)]],
      confirmPassword: ['', Validators.required]
    }, {
      validators: this.passwordsMatchValidator
    });
  }

  passwordsMatchValidator(formGroup: FormGroup) {
    const password = formGroup.get('password').value;
    const confirmPassword = formGroup.get('confirmPassword').value;
    return password === confirmPassword ? null : { passwordsNotMatch: true };
  }

  onSubmit() {
    if (this.passwordForm.valid) {
      // 폼 제출 시 수행할 로직 작성
    }
  }
}

1. 나이 제한 예시:

이 예시는 사용자가 나이를 입력하는 양식을 구현합니다. 나이는 18세 이상이어야 합니다.

htmlCopy code
<form [formGroup]="ageForm" (ngSubmit)="onSubmit()">
  <input type="number" formControlName="age">
  <div *ngIf="ageForm.get('age').invalid && ageForm.get('age').touched">
    <div *ngIf="ageForm.get('age').errors.required">Age is required.</div>
    <div *ngIf="ageForm.get('age').errors.min">Age must be at least 18.</div>
  </div>
  <button type="submit" [disabled]="ageForm.invalid">Submit</button>
</form>
typescriptCopy code
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-age-form',
  templateUrl: './age-form.component.html',
  styleUrls: ['./age-form.component.css']
})
export class AgeFormComponent {
  ageForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.ageForm = this.formBuilder.group({
      age: ['', [Validators.required, Validators.min(18)]]
    });
  }

  onSubmit() {
    if (this.ageForm.valid) {
      // 폼 제출 시 수행할 로직 작성
    }
  }
}




<!-- 비밀번호 유효성 검사 폼 -->
<!-- <form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
  <div>
    <div id="brand_pw" class="py-6 mx-1 flex flex-col">
      <input
        class="placeholder: text-slate-400 space-y-2 w-[465px] h-[56px] rounded-2xl placeholder: pl-4"
        type="password"
        placeholder="비밀번호를 입력해주세요."
        formControlName="password"
      />
      <h6
        class="text-danger"
        [ngClass]="{'text-red-700 font-bold' : passwordInvalid 
      }"
      >
        *비밀번호는 영어, 숫자, 특수문자를 포함한 6자리 으로 설정해주세요
      </h6>
      <button>확인</button>
    </div>
  </div>
</form> -->

<form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
  <input type="text" formGroupName="password" />
  <button>제출</button>
</form>
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  FormsModule,
  ReactiveFormsModule,
  Validators,
} from '@angular/forms';

const pw = /^(?=.[A-Za-z])(?=.\d)(?=.[@$!%#?&])[A-Za-z\d@$!%*#?&]{8,}$/;
// const pw = /[a-z0-9]/;
// const pw = /^[0-9]$/g;

@Component({
  selector: 'app-signup-form',
  templateUrl: './signup-form.page.html',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule],
})
export class SingupFormPage {
  //   private readonly fb = inject(FormBuilder);
  formGroup!: FormGroup;
  // brand_pw_Value: string = '';
  // passwordInvalid: boolean = false;
  // passwordValid: boolean = false;
  //비밀번호 폼을 작성함 조건이 있는 영어 숫자 특수문자를 포함한 6자리

  ngOnInit(): void {}

  constructor(private formBuilder: FormBuilder) {
    this.formGroup = this.formBuilder.group({
      password: ['', [Validators.required, Validators.pattern(pw)]],
    });
  }
  // 폼을 제출 했을때
  onSubmit() {
    if (this.formGroup.invalid) {
      alert('알맞지 않은 형식입니다. ');
    } else {
      console.log('맞음');
    }

 **   // 정규식에 맞지 않는지 여부를 확인 .test() 메서드는 주어진 문자열이 정규식에 맞는지 여부를 불리언 값으로 반환함
    //! 연산자를 사용하여 정규식에 맞지 않는 경우 'true'를 반환
    // this.passwordInvalid =
    //   !/^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6}$/.test(
    //     this.brand_pw_Value
    //   );
    // // invalid가 참이면 valid를 거짓으로 설정 그렇지 않으면 참으로 설정
    // //=> 비밀번호가 유효하지 않으면 valid가 거짓이 되고 유효하면 참
    // this.passwordValid = this.passwordInvalid ? false : true;
    // console.log(this.brand_pw_Value);
    // if (this.formGroup.invalid) {
    //   console.log('안맞음');
    // }**
  }
}

// onSubmit() {
//   if (this.passwordInvalid){
//     //폼이 유효하지 않은 경우에 실행되는 로직
//       //글자가 빨강색으로 변하기

//   const red = FormGroup.get('password').invalid &&(FormGroup.get('password').dirty || formGroup.get('password').touched)
// }

//   else (this.formGroup.valid){
//       const correct =formGroup.get('password').valid && (formGroup.get('password').dirty || formGroup.get('password').touched)
//   }
// }

0개의 댓글