提问人:Roaa Ahmed 提问时间:8/15/2023 最后编辑:Roaa Ahmed 更新时间:8/26/2023 访问量:53
为什么 angular 表单自定义验证不起作用?[已解决]
Why angular form custom validation are not work?[Solved]
问:
**大家好 我有angular项目,对于其中的注册表单,我创建了一个用于密码和另一个用于确认密码的注册表,我收到了两个错误
第一篇:**ERROR TypeError: Cannot read properties of undefined (reading 'registerForm') at confirmationPass (registration.component.ts:53:19)
第二个:
main.ts:8 ERROR Error: NG01052: formGroup expects a FormGroup instance. Please pass one in.
Example:
<div [formGroup]="myGroup">
<input formControlName="firstName">
</div>
In your class:
this.myGroup = new FormGroup({
firstName: new FormControl()
});
at missingFormException (forms.mjs:1436:12)
我registration.ts:
import { Component, ContentChild, OnInit } from '@angular/core';
import { ReactiveFormsModule,FormControl, FormGroup, Validators } from '@angular/forms';
import { faEye, faEyeSlash, faArrowRightToBracket,faCloudUpload} from '@fortawesome/free-solid-svg-icons';
@Component({
selector: 'app-registration',
templateUrl: './registration.component.html',
styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit{
registerForm:FormGroup;
showPassword : boolean= false;
showPasswordCon: boolean = false;
iconof=faEye;
iconshow=faEyeSlash;
iconlogin=faArrowRightToBracket
iconUpload=faCloudUpload;
@ContentChild("inInput") input:any;
constructor(){}
ngOnInit(): void {
this.registerForm= new FormGroup({
fullName:new FormControl(null,Validators.required),
userName:new FormControl(null,[Validators.required,Validators.pattern('^[a-z0-9_-]$')]),
email: new FormControl(null,[Validators.required,Validators.email]),
phoneNumber:new FormControl(null,[Validators.required]),
password:new FormControl(null,[Validators.required,Validators.minLength(8),Validators.maxLength(15),Validators.pattern('(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}')]),
passwordConfirmaton:new FormControl(null,[Validators.required,Validators.minLength(8),Validators.maxLength(15),this.confirmationPass]),
dateOfBirth:new FormControl(null),
addres:new FormControl(null),
userImage:new FormControl(null)
})
}
onSubmite(){
console.log(this.registerForm);
}
toggleShow() {
this.showPassword= !this.showPassword;
if (this.input) {
this.input.type = this.showPassword ? 'text' : 'password';
}
}
toggleShowCon() {
this.showPasswordCon = !this.showPasswordCon;
if (this.input) {
this.input.type = this.showPassword ? 'text' : 'password';
}
}
confirmationPass(){
let pass=this.registerForm.get('password').value
let passCon=this.registerForm.get('passwordConfirmaton').value
if(pass !== passCon){
return{passwordConfirmaton:true};
}else{
return null;
}
}
}
这是我的html:
<!doctype html>
<html lang="en">
<body class="" style="
background:linear-gradient(150deg, rgba(86,171,145,1) 0%, rgba(120,198,163,1) 50%, rgba(153,226,180,1) 67%);">
<section class="ftco-section">
<div class="container">
<div class="row justify-content-start">
<div class="col-md-6 text-start me-5">
<img class="heading-section " src="../assets/imgs/userlogo.png" alt="logo"><i><h3 class=" text-center">Register Form</h3></i>
</div>
<div class="row justify-content-start pe-5">
<div class="col-md-6 col-lg-6">
<div class="login-wrap p-0">
<form [formGroup]="registerForm" (ngSubmit)="onSubmite()" action="#" class="signin-form">
<div class="form-group">
<label>*Full name:</label>
<input formControlName="fullName" id="Fullname-field" type="text" class="form-control" placeholder="FullName" required>
</div>
<div class="form-group">
<label>*User Name:</label>
<input formControlName="userName" id="Username-field" type="text" class="form-control" placeholder="Unique Username" required>
</div>
<div class="form-group">
<label>*Email:</label>
<input formControlName="email" id="email-field" type="email" class="form-control" placeholder="[email protected]" required>
</div>
<div class="form-group">
<label>*Phone Number:</label>
<input formControlName="phoneNumber" id="phoneNumber" type="tel" class="form-control" placeholder="+96653*******" required>
</div>
<div class="form-group">
<label>*Password:</label>
<input formControlName="password" id="password-field" [type]="showPassword? 'text' : 'password'" class="form-control" placeholder="Password" required>
<span class="field-icon" ><a class="type-toggle" (click)="toggleShow()">
<fa-icon class="show-option" style=" color:#4c9781;" [hidden]="!showPassword" [icon]="iconof"></fa-icon>
<fa-icon class="hide-option" style=" color:#4c9781;" [hidden]="showPassword" [icon]="iconshow"></fa-icon>
</a></span>
</div>
<div class="form-group">
<label>*Password Confirmation:</label>
<input formControlName="passwordConfirmaton" id="passwordConf-field" [type]="showPasswordCon? 'text' : 'password'" class="form-control" placeholder="Password Confirmation" required>
<span class="field-icon" ><a class="type-toggle" (click)="toggleShowCon()">
<fa-icon class="show-option" style=" color:#4c9781;" [hidden]="!showPasswordCon" [icon]="iconof"></fa-icon>
<fa-icon class="hide-option" style=" color:#4c9781;" [hidden]="showPasswordCon" [icon]="iconshow"></fa-icon>
</a></span>
</div>
<div class="form-group">
<label>*Birthday Date:</label>
<input formControlName="dateOfBirth" id="DOB" type="date" class="form-control" placeholder="Enter Your Birthday Date" >
</div>
<div class="form-group">
<label>Adress:</label>
<input formControlName="addres" id="adress" type="text" class="form-control" placeholder="Enter Your Addres" >
</div>
<div class="form-group">
<!-- <label>upload Your Image:</label>
<input formControlName="userImage" id="userImage" type="file" class="w-25"> -->
<label for="file-upload" class="custom-file-upload">
<fa-icon [icon]="iconUpload" class="fa-lg"></fa-icon> upload User Image
</label>
<input id="file-upload" type="file"/>
</div>
<div class="form-group">
<button type="submit" class="link form-control btn btn-primary submit px-3">Sign Up</button>
</div>
<div class="form-group d-md-flex">
<div class=" text-md-right">
<span class="link justify-content-center"><a routerLink="/login" style="color: #609696">Log in Here <fa-icon [icon]="iconlogin"></fa-icon></a></span>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
</body>
</html>
**似乎我的代码是正确的,在控制台中我有 erorr,我不知道我能做什么**
答:
3赞
Danil Sereda
8/15/2023
#1
您尝试在验证器中初始化表单之前访问表单
以下是必须如何创建验证器:
创建一个使用以下命令调用的文件:form-validators.ts
export function matchValidator(
matchTo: string,
reverse?: boolean
): ValidatorFn {
return (control: AbstractControl):
ValidationErrors | null => {
if (control.parent && reverse) {
const c = (control.parent?.controls as any)[matchTo]
as AbstractControl;
if (c) {
c.updateValueAndValidity();
}
return null;
}
return !!control.parent &&
!!control.parent.value &&
control.value ===
(control.parent?.controls as any)[matchTo].value
? null
: { matching: true };
};
}
将您的表单修改为:
this.registerForm = new FormGroup({
fullName:new FormControl(null,Validators.required),
userName:new FormControl(null,[Validators.required,Validators.pattern('^[a-z0-9_-]$')]),
email: new FormControl(null,[Validators.required,Validators.email]),
phoneNumber:new FormControl(null,[Validators.required]),
password:new FormControl(null,[Validators.required,Validators.minLength(8),Validators.maxLength(15),Validators.pattern('(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}'),matchValidator('passwordConfirmaton', true)]),
passwordConfirmaton:new FormControl(null,[Validators.required,Validators.minLength(8),Validators.maxLength(15),matchValidator('password')]),
dateOfBirth:new FormControl(null),
addres:new FormControl(null),
userImage:new FormControl(null)
})
当然,别忘了
import matchValidator from "{path}/form-validators.ts"
评论
0赞
Roaa Ahmed
8/15/2023
哇,你是对的,它现在可以工作了.非常感谢您抽出时间和精力帮助我
0赞
Danil Sereda
8/17/2023
如果你选择我的答案作为解决:)那就太好了
0赞
Evgeny Gurevich
8/15/2023
#2
我没有检查过,但我想它应该如下。首先,您需要创建表单,然后才能添加验证函数,因为它在自身内部使用 this.registerForm。
this.registerForm = new FormGroup({
...
passwordConfirmaton:new FormControl(null, [Validators.required, Validators.minLength(8), Validators.maxLength(15)),
...
});
this.registerForm.get("passwordConfirmaton").addValidators([this.confirmationPass])
评论
0赞
Roaa Ahmed
8/15/2023
是的,你是对的,但它的代码仍然不起作用,我有同样的错误,谢谢你的努力
评论