标签: angular-validation

角材料复选框验证

我想知道一种以相同的样式来验证所需复选框的方法,即角材料处理其他控件的验证-在表单提交时,除非触摸,否则控件显示为红色。

我想可以这样做,ng-style但是我想不出一种方法来检查表单是否已提交

这是HTML的代码段

 <form [formGroup]="frmFinish" name="frmFinish">
        <mat-checkbox required formControlName="check1">Discussed Confidentiality and Information Sharing with Service User</mat-checkbox>
        <mat-checkbox required formControlName="check2">Discussed Disposal and Storage of Injecting Equipment and Substances</mat-checkbox>
        <mat-checkbox required formControlName="check3">Discussed Overdose Risk and Prevention</mat-checkbox>

        <mat-form-field>
            <textarea formControlName="note" [(ngModel)]="stepFive.note" matInput placeholder="Any Additional Notes" matTextareaAutosize matAutosizeMinRows="2" matAutosizeMaxRows="5"></textarea>
            <mat-hint align="end">This will be added to the profiles note's</mat-hint>
        </mat-form-field>

        <mat-card-actions>
            <button mat-raised-button type="button" class="nav-btn pull-right" (click)="fillForm()" style="background: red">Fill Form</button>
            <button mat-raised-button class="nav-btn pull-right" style="margin-left:5px;" (click)="createProfile()" type="submit">Finish</button>
            <button mat-raised-button matStepperPrevious class="nav-btn pull-right">Previous</button>
        </mat-card-actions> …
Run Code Online (Sandbox Code Playgroud)

typescript angular-material angular-validation angular

2
推荐指数
1
解决办法
4484
查看次数

在角反应形式验证器中使用google-libphonenumber

这是使用此库的基本用例。我需要验证该号码是否有效。我使用角度反应形式 自定义验证器
验证程序在文件中:validators/phone-number.validator.ts
第一步是获取google-libphonenumber PhoneNumberUtil实例

我的代码的当前状态是:

import { ValidatorFn, AbstractControl } from '@angular/forms';
import phoneUtil = require('google-libphonenumber');
const phoneUtilInstance = phoneUtil.PhoneNumberUtil.getInstance();

export function PhoneNumberValidator(): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } => {
    if (!phoneUtilInstance.isValidNumber(control.value)) {
      return { 'wrongNumber': { value: control.value } };
    }
    return null;
  }
}
Run Code Online (Sandbox Code Playgroud)

以反应形式使用(file contact.component.ts):

import { PhoneNumberValidator } from '@app/validators';
...
ngOnInit(): void { ...
this.editPhoneForm = this.formBuilder.group({
  id: [''],
  phone: ['', [
    Validators.minLength(3),
    PhoneNumberValidator()
  ]], …
Run Code Online (Sandbox Code Playgroud)

typescript libphonenumber angular-validation angular angular-reactive-forms

2
推荐指数
1
解决办法
2481
查看次数

Disable the button when fields are empty in Angular5 [ invalid form ]

I am learning Angular5, new to this.

I have two input fields, one button. Handled validations for that two fields, will enable the button once two fields are entered. I have disable the button when the form is invalid. But it is not working.

<form class="customerRegisteration-form">  
  <div class="form-row">
  <div class="form-group col-md-6">
    <label for="firstName">First Name</label>
      <input required ngModel name="firstName" id="firstName" class="form-control"  placeholder="First Name" #firstName="ngModel"/>
      <div class="alert alert-danger" *ngIf="firstName.touched && !firstName.valid">First Name is required</div>
  </div>
  <div class="form-group col-md-6">
    <label for="lastName">Last Name</label>
    <input …
Run Code Online (Sandbox Code Playgroud)

angular-validation angular

2
推荐指数
1
解决办法
6834
查看次数

显示角反应性形式的错误消息的最佳方法,一种形式控制多个验证错误?

我正在根据建议的角度角度形式验证错误示例方法显示反应形式错误消息。

在页面上显示错误的html代码:

<div [formGroup]="myForm">
  <div>
<input type="text" formControlName="firstName"/>
<div *ngIf="myForm.controls.firstName.invalid"
    class="alert alert-danger">
    <div *ngIf="myForm.controls.firstName.errors.required">
      This Field is Required.
    </div>
    <div *ngIf="myForm.controls.firstName.errors.maxlength">
      your can enter only 50 characters
    </div>
</div>
  </div>
  <div>
<input type="text" formControlName="lastName"/>
<div *ngIf="myForm.controls.lastName.invalid"
    class="alert alert-danger">
    <div *ngIf="myForm.controls.lastName.errors.required">
      This Field is Required.
    </div>
    <div *ngIf="myForm.controls.lastName.errors.maxlength">
      your can enter only 50 characters
    </div>
</div>
  </div>
  </div>
Run Code Online (Sandbox Code Playgroud)

仅供参考以下我的组件代码:

this.myForm = this.formBuilder.group({
      firstName:['',[Validators.required,Validators.maxLength(50)]],
      lastName:['',[Validators.required,Validators.maxLength(50)]]
    })
Run Code Online (Sandbox Code Playgroud)

如果看到上面的代码,则对我的firstName和lastName字段应用了两个验证。

为了显示错误消息,我编写了多个* ngIf条件来显示错误消息。

有什么最好的方法来显示特定控件的验证消息而无需编写多个* ngIf条件?,因为我一次又一次地编写相同的代码,而使用不同的控件名称和验证者名称来显示错误消息。

angular-ng-if angular-validation angular

2
推荐指数
4
解决办法
1万
查看次数

在 formArray 中验证 formGroup 的问题

我正在创建一个带有角材料垫表的表格。

我在编写我的应用程序时使用反应式表单,表单启动看起来像这样:

myForm = this.fb.group({
    settings: this.fb.array([])
});
Run Code Online (Sandbox Code Playgroud)

我的表单是一个 formGroup,其中包含一个 formArray 控件(设置)。

设置 formArray 包含每个设置的 formGroup (mat-table 中的每一行都是一个 formGroup 并包含多个控件)。

当我尝试向其添加验证时,我的问题就开始了。

如果我只有一个带有 formControl 的 formGroup 并且其中一个是 Validators.required ,例如,表单是无效的,直到我添加了一些值,然后它才会变为有效状态。

然而,在表单数组中使用 formGroup 时,即使在向 require 字段添加一些值后,表单状态仍然无效(我什至控制台记录表单以查看内部值是否已更改)。

此外,当我尝试使用 valueChange().subscribe 捕捉更改时,仅当我从 formArray 推送/删除组时才会触发该事件,而不会在更改设置组内的现有控件时触发该事件。

如何在数组内的组中侦听内部更改事件,然后对它们使用一些自定义估值?

angular-validation angular angular-reactive-forms

2
推荐指数
2
解决办法
6578
查看次数

How to create a custom form validator to accept only valid JSON in Angular

In my Angular app, I have a reactive form which for simplicity I will assume to have only one control called configJson which is represented by a <textarea> in the DOM.

I need to validate this form control to only accept valid JSON text from the user input, and display an error message otherwise.

Here's my component's class and template:

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

@Component({
  selector: 'app-configuration',
  templateUrl: './configuration.component.html',
  styleUrls: …
Run Code Online (Sandbox Code Playgroud)

json typescript angular-validation angular angular-reactive-forms

2
推荐指数
2
解决办法
5057
查看次数

您如何确定在 angular 8 中哪个验证器条件失败

例如我有一个输入,我添加了多验证条件,如:required、mail和pattern,所以任何一个失败都会导致controls.status给我“INVALID”,如果我想知道哪个失败了我该怎么办?

angular-validation angular angular-validator

2
推荐指数
2
解决办法
4062
查看次数

如何将自定义验证器添加到 FormArray?

我想向表单添加自定义验证器,以防止 mat-step 切换到下一步。当我使用 FormGroups 时一切正常,但是当我必须使用 FormArray 时我无法实现验证。

我已经尝试了至少两种在表单初始化时分配验证器的变体:

  • 数组内部

statuses: this._formBuilder.array([this.createStatus()], defaultStatusValidator())

  • 数组的父形式内部

this.productionLineStatuses = this._formBuilder.group({statuses: this._formBuilder.array([this.createStatus()])}, {validator: defaultStatusValidator()});

但是这种尝试会导致错误(可能是在铸造验证器时):

TypeError: Cannot convert undefined or null to object 
    at Function.keys (<anonymous>)
    at FormGroup.validate [as validator] (default-status.directive.ts:6)
    at FormGroup._runValidator (forms.js:3438)
    at FormGroup.updateValueAndValidity (forms.js:3399)
    at new FormGroup (forms.js:4097)
    at FormBuilder.group (forms.js:7578)
    at CreateProductionLineComponent.ngOnInit (create-production-line.component.ts:31)
Run Code Online (Sandbox Code Playgroud)

在以下情况下不会抛出错误,但验证器也不起作用。这是我的其余代码和我的自定义验证器:

TypeError: Cannot convert undefined or null to object 
    at Function.keys (<anonymous>)
    at FormGroup.validate [as validator] (default-status.directive.ts:6)
    at FormGroup._runValidator (forms.js:3438)
    at FormGroup.updateValueAndValidity (forms.js:3399)
    at new FormGroup (forms.js:4097)
    at …
Run Code Online (Sandbox Code Playgroud)

angular-material angular-validation angular angular-forms

2
推荐指数
1
解决办法
8162
查看次数

不推荐使用 Angular FormBuilder 组

我看到有一个主题看起来像我的,但它并没有真正回答我的问题,因为我们没有以相同的方式管理错误。不推荐使用 FormBuilder 组

首先,我刚刚迁移到 Angular 11,现在遇到了这个问题:

group is deprecated: This api is not typesafe and can result in issues with Closure Compiler renaming.
Use the `FormBuilder#group` overload with `AbstractControlOptions` instead.
Run Code Online (Sandbox Code Playgroud)

在此页面中,我会在页面上自动生成许多表单,在日期范围的情况下,我使用两个日期选择器。我创建了一个函数来检查 2 个日期选择器中的值。

成分:

newGroup = this.fb.group(
        {
          [node.type + '_' + node.objectId + '_dateFrom']: [
            '',
            [Validators.required]
          ],
          [node.type + '_' + node.objectId + '_dateTo']: [
            '',
            [Validators.required]
          ]
        },
        {
          validator: CheckFromToDate(
            node.type + '_' + node.objectId + '_dateFrom',
            node.type + '_' + node.objectId + '_dateTo'
          ) …
Run Code Online (Sandbox Code Playgroud)

angular2-forms angular2-formbuilder angular-validation angular angular2-form-validation

2
推荐指数
1
解决办法
1986
查看次数

如何在角度模板驱动的方法中验证开始和结束日期?

我的表单中有 2 个日期输入,如下所示:

<label class="control-label">Start Date</label>
    <input type="date" name="startDate" placeholder="Start Date" class="form-control" ngModel required #startDate="ngModel">
    <span *ngIf="!startDate.valid && startDate.touched" class="error-msg">
     <span *ngIf="startDate.errors.required">Start Date is required</span>
     </span>
     <br/>
 <label class="control-label">End Date</label>
 <input type="date" name="endDate" placeholder="End Date" class="form-control" ngModel required #endDate="ngModel" >
    <span *ngIf="!endDate.valid && endDate.touched" class="error-msg">
    <span *ngIf="endDate.errors.required">End Date is required</span>
    </span>
Run Code Online (Sandbox Code Playgroud)

而且我想允许用户仅从开始日期中选择日期。我尝试使用该min属性但不起作用

date angular-validation angular

1
推荐指数
1
解决办法
3930
查看次数