我有这个表格
@Component({
template: `
<form [formGroup]="formGroup" (ngSubmit)="onSubmit()" novalidate>
<input name="detail" id="detail" formControlName="detail"></input>
<div *ngIf="formGroup.controls['detail'].dirty && formGroup.controls['detail'].invalid">This is required</div>
<button type="submit" >Post</button>
</form>
`,
})
export class CreateDiscussionComponent {
formGroup: FormGroup;
submitted: boolean = false;
constructor(
) {
this.formGroup = new FormGroup({
detail: new FormControl('', [Validators.required, Validators.minLength(2) ]),
});
}
onSubmit(): void {
this.submitted = true;
console.log( this.submitted)
}
}
它的作用是,当我点击提交或输入时提交表格。
问题:当我提交空值时,它将允许提交。这很糟糕。
它不应该允许并显示错误。
答案 0 :(得分:3)
您需要Validators.compose
。试试下面的例子。而且,在提交按钮中添加[disabled]="!form.valid"
也不错。
<强> myform.html 强>
<div>
<form [formGroup]="form" (ngSubmit)="onSubmit(form.value)">
<div class="form-group row">
<label for="zipCode" class="col-sm-2 control-label">Zip Code</label>
<input [formControl]="zipCode" type="text" class="form-control" id="zipCode" placeholder="Enter your Zip Code">
</div>
<div class="form-group row">
<button [disabled]="!form.valid" type="submit" class="btn btn-default">Request</button>
</div>
</form>
</div>
<强> myform.ts 强>
import {Component, ViewEncapsulation} from '@angular/core';
import {FormGroup, AbstractControl, FormBuilder, Validators} from '@angular/forms';
@Component({
selector: 'myform',
encapsulation: ViewEncapsulation.None,
template: require('./myform.html')
})
export class MyForm {
public form:FormGroup;
public zipCode:AbstractControl;
public submitted:boolean = false;
constructor(fb:FormBuilder) {
this.form = fb.group({
'zipCode': ['', Validators.compose([Validators.required, Validators.minLength(6)])]
});
this.zipCode = this.form.controls['zipCode'];
}
public onSubmit(values:Object):void {
this.submitted = true;
if (this.form.valid) {
console.log("FORM VALUES: "+values);
}
}
}
答案 1 :(得分:2)
您的错误<input name="detail" id="detail" formControlName="detail"></input>
,输入为无效元素,请勿填写结尾标记。
顺便说一下,你有2个验证器,你需要传播错误信息:
在线演示:https://plnkr.co/edit/PVndhkpyfY6s1iq5RPsY?p=preview
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms'
@Component({
selector: 'app-root',
template: `
<form [formGroup]="formGroup" (ngSubmit)="onSubmit()" novalidate>
<input name="detail" id="detail" formControlName="detail">
<div *ngIf="formGroup.get('detail').dirty && formGroup.get('detail').hasError('required')">This is required</div>
<div *ngIf="formGroup.get('detail').dirty && formGroup.get('detail').hasError('minlength')">
This field requires min length: {{ formGroup.get('detail').errors.minlength?.requiredLength }},
actual length: {{ formGroup.get('detail').errors.minlength?.actualLength }}
</div>
<div><button type="submit" [disabled]="formGroup.invalid">Post</button></div>
</form>
`
})
export class AppComponent implements OnInit {
formGroup: FormGroup;
submitted: boolean = false;
constructor(
) {
this.formGroup = new FormGroup({
detail: new FormControl('', [Validators.required, Validators.minLength(2) ]),
});
}
onSubmit(): void {
console.log(this.formGroup);
this.submitted = true;
if (this.formGroup.valid) {
console.log( this.submitted);
// do submit form data to server
}
}
}
答案 2 :(得分:0)
在下面找到非常简单的代码: HTML代码
<div class="col-md-4 col-md-offset-4" >
<form name="signup_form" (ngSubmit)="fs.form.valid && signup(fs);" #fs="ngForm" novalidate>
<div class="formbox">
<div class="inputbox">
<div class="form-group" [ngClass]="{ 'has-error': fs.submitted && !fullname.valid }">
<input type="text" class="form-control" name="name" id="name" placeholder="Name" name="fullname" [(ngModel)]="user.fullName" minlength="6" #fullname="ngModel" required pattern="^[A-Za-z ]+$"/>
<div *ngIf="fs.submitted && !fullname.valid" class="help-block">Full Name is required and must be a valid name</div>
</div>
<div class="form-group" [ngClass]="{ 'has-error': fs.submitted && !email.valid }">
<input type="email" class="form-control" name="email" id="email" placeholder="Email" [(ngModel)]="user.email" #email="ngModel" pattern="^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" required/>
<div *ngIf="fs.submitted && !email.valid" class="help-block">Invalid Email</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="phone_number" id="phone_number" placeholder="Phone No." [(ngModel)]="user.phone" maxlength="12" minlength="10" #phone="ngModel" required/>
<div *ngIf="fs.submitted && !phone.valid" class="help-block">Enter valid phone</div>
</div>
<div class="form-group" [ngClass]="{ 'has-error': fs.submitted && !password.valid }">
<input type="password" class="form-control" name="password" id="user_password" placeholder="Password" [(ngModel)]="user.password" #password="ngModel" required/><!--pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{6,12}$" -->
<div *ngIf="fs.submitted && !password.valid && (password.touched && password.errors?.required)" class="help-block">Password is required and must be atleast six characters long.</div>
</div>
<div class="form-group">
<input type="password" class="form-control" name="confirm_password" id="confirm_password" placeholder="Confirm Password" [(ngModel)]="confirm_password" #confirmPassword="ngModel" required appConfirmEqualValidator='password'/>
<div *ngIf="fs.submitted && (confirmPassword.touched && confirmPassword.errors?.notEqual && !confirmPassword.errors?.required)" class="help-block" >Password Mismatch</div>
</div>
<div class="form-group">
<div class="checkboxrow">
<input type="checkbox" id="test1" name="cb" #cb="ngModel" [(ngModel)]="user.cb" [required]="user.cb==null">
<label for="test1" control-labekl>Agree with terms and conditions</label>
<div *ngIf="fs.submitted && !cb.valid" class="help-block" >Please agree with terms and conditions</div>
</div>
</div>
<div class="form-group">
<span style="text-align: center;color: #a94442">{{errorMsg}}</span>
<span style="text-align: center;color: #28a745">{{sucsMsg}}</span>
<button type="submit" class="btn btn-primary signin">Sign Up <span class="arrowbtn"><span class="fa fa-arrow-right"></span></span></button>
</div>
</div>
<div class="registerrow text-center">Already have an account ? <a href="javascript:void(0)" id="loginshow">Login here !</a></div>
</div>
</form>
</div>
ts文件的代码:
import { Validator,NG_VALIDATORS, AbstractControl } from '@angular/forms';
import { Directive, Input } from '@angular/core';
@Directive({
selector:'[appConfirmEqualValidator]',
providers: [{
provide: NG_VALIDATORS,
useExisting: ConfirmEqualValidatorDirective,
multi: true
}]
})
export class ConfirmEqualValidatorDirective implements Validator {
@Input() appConfirmEqualValidator: string;
validate(control: AbstractControl):{[key:string]: any} |null {
const controlToCompare = control.parent.get(this.appConfirmEqualValidator);
if(controlToCompare && controlToCompare.value !==control.value){
return { 'notEqual': true}
}
return null;
}
}