programing

공백/빈 공간의 유효성을 검사하는 방법은 무엇입니까?[각도 2]

codeshow 2023. 9. 4. 20:50
반응형

공백/빈 공간의 유효성을 검사하는 방법은 무엇입니까?[각도 2]

각진 2 형태의 공백/공백을 피하고 싶습니다.가능합니까?이것이 어떻게 행해지는가?

이를 처리할 사용자 정의 검증기를 생성할 수 있습니다.

new FormControl(field.fieldValue || '', [Validators.required, this.noWhitespaceValidator])

구성 요소에 noWhitespaceValidator 메서드 추가

public noWhitespaceValidator(control: FormControl) {
    return (control.value || '').trim().length? null : { 'whitespace': true };       
}

그리고 HTML에서.

<div *ngIf="yourForm.hasError('whitespace')">Please enter valid data</div>

간단하고 깨끗한 해결책은 패턴 검증을 사용하는 것이라고 생각합니다.

다음 패턴공백으로 시작하는 문자열을 허용하고 공백만 포함하는 문자열을 허용하지 않습니다.

/^(\s+\S+\s*)*(?!\s).*$/

폼 그룹의 해당 컨트롤에 대한 검증자를 추가할 때 설정할 수 있습니다.

const form = this.formBuilder.group({
            name: ['', [
                Validators.required,
                Validators.pattern(/^(\s+\S+\s*)*(?!\s).*$/)
            ]]
        });

이 기사가 http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/ 에 도움이 될 수도 있습니다.

이 접근 방식에서는 FormControl을 사용한 다음 값 변화를 지켜본 다음 값에 마스크를 적용해야 합니다.예는 다음과 같습니다.

...
form: FormGroup;
...


ngOnInit(){
    this.form.valueChanges
            .map((value) => {
                // Here you can manipulate your value
                value.firstName = value.firstName.trim();
                return value;
            })
            .filter((value) => this.form.valid)
            .subscribe((value) => {
               console.log("Model Driven Form valid value: vm = ",JSON.stringify(value));
            });

}

Angular 6의 텍스트 상자에 공백을 입력하지 않음

<input type="text" (keydown.space)="$event.preventDefault();" required />
    export function noWhitespaceValidator(control: FormControl) {
       const isSpace = (control.value || '').match(/\s/g);
       return isSpace ? {'whitespace': true} : null;
}

사용할

 password: ['', [Validators.required, noWhitespaceValidator]]

템플릿/html 내

<span *ngIf="newWpForm.get('password').hasError('whitespace')">
    password cannot contain whitespace
</span>

Angular Reactive Forms를 사용하는 경우 Validator 기능이 있는 파일을 만들 수 있습니다.이렇게 하면 공백만 입력할 수 없습니다.

import { AbstractControl } from '@angular/forms';
export function removeSpaces(control: AbstractControl) {
  if (control && control.value && !control.value.replace(/\s/g, '').length) {
    control.setValue('');
  }
  return null;
}

그런 다음 구성 요소 유형 스크립트 파일에서 다음과 같은 검증자를 사용합니다.

this.formGroup = this.fb.group({
  name: [null, [Validators.required, removeSpaces]]
});

또는 Angular pattern validator를 사용하여 공백이 아닌 문자를 일치시킬 수도 있습니다.

const nonWhitespaceRegExp: RegExp = new RegExp("\\S");

this.formGroup = this.fb.group({
  name: [null, [Validators.required, Validators.pattern(nonWhiteSpaceRegExp)]]
});

제가 한 일은 minLength에 대해 트림()을 추가한 것을 제외하고는 각도와 동일한 작업을 수행하는 검증기를 만들었습니다.

import { Injectable } from '@angular/core';
import { AbstractControl, ValidatorFn, Validators } from '@angular/forms';


@Injectable()
export class ValidatorHelper {
    ///This is the guts of Angulars minLength, added a trim for the validation
    static minLength(minLength: number): ValidatorFn {
        return (control: AbstractControl): { [key: string]: any } => {
            if (ValidatorHelper.isPresent(Validators.required(control))) {
                return null;
            }
             const v: string = control.value ? control.value : '';
            return v.trim().length < minLength ?
                { 'minlength': { 'requiredLength': minLength, 'actualLength': v.trim().length } } :
                null;
        };
    }

    static isPresent(obj: any): boolean {
        return obj !== undefined && obj !== null;
    }
}

그런 다음 app.component.ts에서 각도에서 제공하는 minLength 함수를 재정의합니다.

import { Component, OnInit } from '@angular/core';    
import { ValidatorHelper } from 'app/common/components/validators/validator-helper';
import { Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {  
  constructor() { }

  ngOnInit(): void {       
    Validators.minLength = ValidatorHelper.minLength;
  }
}

이제 각도의 minLength 내장 검증기가 모든 곳에서 사용되며 도우미에서 생성한 minLength를 사용합니다.

Validators.compose([
      Validators.minLength(2)         
    ]);

반응형 양식과 함께 다음 지침을 사용하여 모든 양식 필드를 자를 수 있습니다.Validators.required정상 작동:

@Directive({
  selector: '[formControl], [formControlName]',
})
export class TrimFormFieldsDirective {
  @Input() type: string;

  constructor(@Optional() private formControlDir: FormControlDirective, 
              @Optional() private formControlName: FormControlName) {}

  @HostListener('blur')
  @HostListener('keydown.enter')
  trimValue() {
    const control = this.formControlDir?.control || this.formControlName?.control;
    if (typeof control.value === 'string' && this.type !== 'password') {
      control.setValue(control.value.trim());
    }
  }
}

이것은 저에게 효과가 있었던 아래의 하나에 대한 약간 다른 대답입니다.

public static validate(control: FormControl): { whitespace: boolean } {
    const valueNoWhiteSpace = control.value.trim();
    const isValid = valueNoWhiteSpace === control.value;
    return isValid ? null : { whitespace: true };
}

제출을 을▁use오시▁to▁just▁subm사십▁the▁form용하,를 사용하면 됩니다.required입력 필드에 특성을 입력합니다.

<input type="text" required>

또는 제출 후

양식을 제출할 때 str.trim()을 사용하여 문자열의 시작과 끝에서 공백을 제거할 수 있습니다.다음을 보여주기 위해 제출 기능을 수행했습니다.

submitFunction(formData){

    if(!formData.foo){
        // launch an alert to say the user the field cannot be empty
        return false;
    }
    else
    {
        formData.foo = formData.foo.trim(); // removes white 
        // do your logic here
        return true;
    }

}

입력 필드에서 모든 공백을 자동으로 제거하려면 사용자 정의 검증자를 만들어야 합니다.

removeSpaces(c: FormControl) {
  if (c && c.value) {
    let removedSpaces = c.value.split(' ').join('');
    c.value !== removedSpaces && c.setValue(removedSpaces);
  }
  return null;
}

입력된 텍스트와 붙여넣기 텍스트로 작동합니다.

저는 이름과 성에 필수 필드인 사용자 입력이 있고 사용자가 첫 번째 문자로 공백을 입력할 수 없다는 요구 사항이 있었습니다.

node_modules에서 AbstractControl을 가져옵니다.

import { AbstractControl } from '@angular/forms';

첫 번째 문자가 공백인지 확인합니다. "예"인 경우 값을 비워두고 필요한 값을 반환합니다. true.반환이 없는 경우 null

export function spaceValidator(control: AbstractControl) {
if (control && control.value && !control.value.replace(/\s/g, '').length) {
    control.setValue('');
    console.log(control.value);
    return { required: true }
}
else {
    return null;
}
}

위의 코드는 첫 번째 문자가 공백이면 오류를 트리거하고 공백이 첫 번째 문자가 되도록 허용하지 않습니다.

그리고 정보 작성자 그룹 선언

this.paInfoForm = this.formBuilder.group({
        paFirstName: ['', [Validators.required, spaceValidator]],
        paLastName: ['', [Validators.required, spaceValidator]]
})

입력에서 시작할 때 빈 공간을 확인하려면 변경 이벤트를 호출하고 이에 대한 인라인 기능을 수행하면 됩니다.

<input type="text" class="form-control"                     
            placeholder="First Name without white space in starting"
            name="firstName"
            #firstName="ngModel"
            [(ngModel)]="user.FirstName"
            (change) ="user.FirstName = user.FirstName.trim()"
            required/>

Angular 2+에서 반응형을 사용하는 경우 다음을 사용하여 선행 및 후행 공백을 제거할 수 있습니다.(blur)

앱.스캐너

<input(blur)="trimLeadingAndTrailingSpaces(myForm.controls['firstName'])" formControlName="firstName" />

앱.ts

public trimLeadingAndTrailingSpaces(formControl: AbstractControl) {
    if (formControl && formControl.value && typeof formControl.value === 'string') {
        formControl.setValue(formControl.value.trim());
    }
}

app.component.html에서

<form [formGroup]="signupForm">

           <input  type="text" name="name" [formControl]="signupForm.controls['name']"
              placeholder="First Name"
              required
            />
     <small
            *ngIf="signupForm.controls['name'].hasError('pattern')"
            class="form-error-msg"
            >First Name without space</small>

    </form>

app.component.ts 파일에서

import { Validators, FormGroup, FormControl } from "@angular/forms";
signupForm: FormGroup;
ngOnInit(){
this.signupForm = new FormGroup({
  name: new FormControl("", [
    Validators.required,
    Validators.pattern("^[a-zA-Z]+$"),
    Validators.minLength(3)
  ])
})

많은 시도 끝에 나는 발견했습니다.[a-zA-Z\\s]*공백이 있는 영숫자의 경우

예:

뉴욕

뉴델리

양식 값 변경 기능을 사용하여 공백을 방지했습니다.필요한 유효성 검사 후 모든 필드를 트리밍할 때마다 빈 문자열에 대해 작동합니다.

여기처럼:-

this.anyForm.valueChanges.subscribe(data => {
   for (var key in data) {
        if (data[key].trim() == "") {
          this.f[key].setValue("", { emitEvent: false });
        }
      }
    }

편집됨 --

폼 컨트롤에서 숫자/숫자로 작업하는 경우 트림 기능이 작동하지 않는 경우 다음과 같이 직접 사용합니다.

this.anyForm.valueChanges.subscribe(data => {
  for (var key in data) {
        if (data[key] && data[key].toString().trim() == "") {
          this.f[key].setValue("", { emitEvent: false });
        }
      }  
  }

in hello.component.html

<input [formControl]="name" />
<div *ngIf="name.hasError('trimError')" > {{ name.errors.trimError.value }} </div>

안녕하세요.component.ts.

import { ValidatorFn, FormControl } from '@angular/forms';

const trimValidator: ValidatorFn = (text: FormControl) => {
  if (text.value.startsWith(' ')) {
    return {
      'trimError': { value: 'text has leading whitespace' }
    };
  }
  if (text.value.endsWith(' ')) {
    return {
      'trimError': { value: 'text has trailing whitespace' }
    };
  }
  return null;
};`

export class AppComponent {
  control = new FormControl('', trimValidator);
}

코드 예제

export function NoWhitespaceValidator(): ValidatorFn {
    return (control: AbstractControl): any => {
        window.setTimeout(() => {
            if (control.value && control.value != '') {
                let trimedvalue = control.value.replace(/\s/g, '');
                control.setValue(trimedvalue);
            }
        }, 10);
    };
}


username: ['', Validators.compose([Validators.required, NoWhitespaceValidator()])],

파티에 늦었지만 대부분의 답변이 제 사용 사례에 제대로 작동하지 않는다는 것을 알게 되었습니다.UTF 8 Whitespace를 올바르게 탐지하는 정규식 일치를 사용하고 있습니다(.trim()는 그렇지 않습니다).또한 null 값 검사를 추가했습니다.코드는 typescript이지만 javascript로 변환하기 쉬울 것입니다.

notOnlyWhitespaceValidator(control: AbstractControl) {
    const isWhitespace = control.value && control.value.length > 0 && (control.value as string).match(/[^-\s]/) === null;
    const isValid = !isWhitespace;
    return isValid ? null : { 'only-whitespace': true };
  }

여기 테스트 스위트가 있습니다(농담).

  describe('notOnlyWhitespaceValidator', () => {
    it('should not trigger on missing value', () => {
      expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl(''))).toEqual(null);
      expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl())).toEqual(null);
    });

    it('should trigger on only whitespace', () => {
      expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl(' '))).toEqual({ 'only-whitespace': true });
      expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl('\n'))).toEqual({ 'only-whitespace': true });
      // check utf 8 zero with space
      const utf8Space = '\ufeff';
      expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl(utf8Space))).toEqual({
        'only-whitespace': true,
      });
    });

    it('should not trigger on valid input', () => {
      expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl(' Whatever is valid '))).toEqual(null);
      expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl('!'))).toEqual(null);
    });
  });

단순히 패턴 검증기를 추가할 수 있습니다.

Validators.pattern('[\\S]{1,}[\\S\\s]*|[\\s]*[\\S]{1,}[\\S\\s]*')

이렇게 하면 선행 섹션 또는 이후 섹션에 공백이 있는지 확인할 수 있습니다.

Angular 코드를 사용하여 사용자 정의 검증기를 만들고 다음과 같이 사용자 정의하는 것이 좋습니다.

export function required(control: AbstractControl): ValidationErrors | null {
  return isEmptyInputValue(control?.value) ? {'required': true} : null;
}

function isEmptyInputValue(value: any): boolean {
  return value == null ||
    (typeof value === 'string' && value.trim().length === 0) ||
    (Array.isArray(value) && value.length === 0);
}

그러면 당신은 당신의 것을 사용할 수 있습니다.required각진 것 대신에 검증자.

언급URL : https://stackoverflow.com/questions/39236992/how-to-validate-white-spaces-empty-spaces-angular-2

반응형