typescript Angular 6输入表单验证

h9a6wy2h  于 2022-11-18  发布在  TypeScript
关注(0)|答案(5)|浏览(222)

我有3个输入字段,主要是必需的,但现在我想把逻辑,如果其中一个被填写,那么其余的两个不应该是必需的了。某种程度上它的工作正常,但问题是,如果我填写的形式,然后删除值(所以形式基本上是空的),它保持形式有效。
所以我键入Uname:abc 形式有效,但如果删除Uname --〉形式则无效
现在第二次输入如果我填写用户名:abcdef 格式有效
现在如果我删除用户名

表单仍然有效

下面是我的堆栈 lightning 战:
https://stackblitz.com/edit/angular-5l9kb4

ffscu2ro

ffscu2ro1#

使用下面的代码

checkValue() {
this.myForm.get("Uname").valueChanges.subscribe(value => {
  if (value  && value.length > 0) {
    this.myForm.controls["username"].clearValidators();
    this.myForm.controls["username"].updateValueAndValidity();
    this.myForm.controls["description"].clearValidators();
    this.myForm.controls["description"].updateValueAndValidity();
  }
});
this.myForm.get("username").valueChanges.subscribe(value => {
  if (value  && value.length > 0) {
    this.myForm.controls["description"].clearValidators();
    this.myForm.controls["description"].updateValueAndValidity();
    this.myForm.controls["Uname"].clearValidators();
    this.myForm.controls["Uname"].updateValueAndValidity();
  }
});
this.myForm.get("description").valueChanges.subscribe(value => {
  if (value && value.length > 0) {
    this.myForm.controls["username"].clearValidators();
    this.myForm.controls["username"].updateValueAndValidity();
    this.myForm.controls["Uname"].clearValidators();
    this.myForm.controls["Uname"].updateValueAndValidity();
  }
});

Stackblitz工作示例。
我已经添加了一个简单的条件value.length > 0来检查最小长度。如果你愿意,你可以添加更多的验证。我希望它能解决你的问题。

yacmzcpb

yacmzcpb2#

首先检查onTypeChange($event.target.value)函数

<form [formGroup]="myForm" (ngSubmit)="submit(myForm.value)">

 <mat-form-field class="full-width">
   value 1
      <input matInput type="text" formControlName="Uname" (input)="onTypeChange($event.target.value)">
    </mat-form-field>

    <mat-form-field class="full-width">vlaue 2
      <input matInput type="text" formControlName="username" (input)="onTypeChange($event.target.value)">
    </mat-form-field>

    <mat-form-field class="full-width" >
      value 3
      <input matInput type="text" formControlName="description"  (input)="onTypeChange($event.target.value)">
    </mat-form-field>
  <button mat-raised-button type="submit" [disabled]="!myForm.valid">Submit</button>
</form>

.ts档案

onTypeChange(searchValue : string ) 
     {     
      console.log("typed value"+searchValue);}
      }

 submit(myForm)
  {
        console.log(myForm);
  }
x6h2sr28

x6h2sr283#

我还没有使用被动式表单验证,但已完全满足您的要求。请检查以下代码:小提琴链接:disable form button on condition

import { Component,OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray,
 } from "@angular/forms";
import { FormControl } from '@angular/forms';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
  name = 'Angular';
  myForm:FormGroup;
  Uname:any;
  username:any;
  description:string;
  constructor(private fb:FormBuilder) {
  }
  ngOnInit() {
  }

  checkForm() {
    console.log(typeof this.Uname,this.username,this.description)
    if((typeof this.Uname !== 'undefined' && this.Uname != '') || (typeof this.username !== 'undefined' && this.username != '') || (typeof this.description !== 'undefined' && this.description != ''))
      return false;
    else 
      return true;
  }
}
<form name="Mainform" id="Mainform"  (ngSubmit)="submit(myForm.value)">

 <mat-form-field class="full-width">
      <input matInput type="text" 
      name="Uname"
      [(ngModel)]="Uname">
    </mat-form-field>

    <mat-form-field class="full-width">
      <input matInput type="text" 
      [(ngModel)]="username" name="username" >
    </mat-form-field>

    <mat-form-field class="full-width">
      <input matInput type="text" 
      [(ngModel)]="description" name="description">
    </mat-form-field>
  <button mat-raised-button type="submit" [disabled]="checkForm()">Submit</button>
</form>
mwkjh3gx

mwkjh3gx4#

当这个值存在时,你的代码会清除验证器。现在,当你删除添加的值时,你的代码什么也不做。你必须重新添加验证器。
最好的方法是向整个窗体组添加自定义验证程序。此验证程序将有权访问组中的所有控件。请删除每个窗体控件上的订阅。

this.myForm = fb.group({
  Uname : [''],
  username : [''],
  description : ['']

},{ validator: formValidator });

function formValidator(formGroup: FormGroup) {
  const uName = formGroup.controls['Uname'].value;
  const username = formGroup.controls['username'].value;
  const description = formGroup.controls['description'].value;
  return uName === '' && username === '' && description === '' ? { 
  oneFieldRequired: {valid: false} } : null;
}
hs1ihplo

hs1ihplo5#

理想情况下,这应该是FormGroup验证器的职责。我建议您创建一个自定义验证器来验证整个FormGroup,因为这正是您所追求的:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray } from "@angular/forms";
import { FormControl } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  myForm: FormGroup;

  constructor(private readonly fb: FormBuilder) { }

  ngOnInit() {
    this.myForm = this.fb.group({
      uName: [''],
      username: [''],
      description: ['']
    }, { validators: anyOneFieldRequired });
  }

  submit(value) {
    console.log('Form Value: ', value);
  }
}

function anyOneFieldRequired(formGroup: FormGroup) {
  const uName = formGroup.controls['uName'].value;
  const username = formGroup.controls['username'].value;
  const description = formGroup.controls['description'].value;
  return uName === '' && username === '' && description === '' ? { oneFieldRequired: true } : null;
}

在您的模板中:

<form [formGroup]="myForm" (ngSubmit)="submit(myForm.value)">
    <mat-form-field class="full-width">
        <input matInput type="text" formControlName="uName">
  </mat-form-field>

  <mat-form-field class="full-width">
    <input matInput type="text" formControlName="username" >
  </mat-form-field>

  <mat-form-field class="full-width">
    <input matInput type="text" formControlName="description">
  </mat-form-field>

  <button mat-raised-button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>

这里有一个Working Sample StackBlitz给你的参考。

相关问题