在使用Angular4实现单个输入字段的多重验证时,我收到以下错误。
错误:
ERROR in src/app/about/about.component.ts(30,7): error TS1117: An object literal cannot have multiple properties with the same name in strict mode.
src/app/about/about.component.ts(30,7): error TS2300: Duplicate identifier 'url
这是我的代码:
about.component.html:
<form [formGroup]="textForm" (ngSubmit)="onTextFormSubmit()">
<input type="text" placeholder="please enter url" formControlName="url" id="weburl"><label *ngIf="textForm.get('url').invalid && processValidation" [ngClass] = "'error'"> Url is required. </label>
<button type="submit">ADD</button>
</form>
about.component.ts:
export class AboutComponent implements OnInit {
private headers = new Headers({'Content-Type':'application/json'});
aboutData = [];
processValidation = false;
pattern="/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/";
filePath:string;
filelist: Array<{filename: string, intkey: string}> = [{
filename: 'http://oditek.in/jslib/jslib.js',
intkey: 'aboutlib'
},{
filename: 'http://oditek.in/jslib/aboutjs.js',
intkey: 'aboutjs'
}];
textForm = new FormGroup({
url: new FormControl('', Validators.required),
url: new FormControl('', Validators.pattern(this.pattern))
});
constructor(private router:Router,private route:ActivatedRoute,private http:Http) { }
ngAfterViewChecked() {
$('#title').attr('style','font-weight:bold');
/*$.getScript(this.filePath,function(){
setTimeout(function(){
checkJS();
}, 5000);
})*/
}
ngOnInit() {
this.route.params.subscribe(params=>{
this.filelist.forEach(item => {
let parampath=atob(params['filepath']);
if(item.intkey==parampath)
this.filePath = item.filename;
else
return;
});
});
this.http.get('http://localhost:3000/articles').subscribe(
(res:Response)=>{
this.aboutData = res.json();
}
)
}
onTextFormSubmit(){
this.processValidation = true;
if (this.textForm.invalid) {
return;
}
let url = this.textForm.value;
}
}
我需要单输入字段的空白字段和模式验证。所有相应的错误消息将显示在输入字段下方,但我收到此错误。
答案 0 :(得分:1)
您创建url
FormControl是错误的,因为您不需要创建两个控件。您应该结合验证器:
解决方案1:
textForm = new FormGroup({
url: new FormControl('', Validators.compose([Validators.required, Validators.pattern(this.pattern)]))
});
解决方案2:
textForm = new FormGroup({
url: new FormControl('', [Validators.required, Validators.pattern(this.pattern)])
});
答案 1 :(得分:1)
问题出在你的代码中:
textForm = new FormGroup({
url: new FormControl('', Validators.required),
url: new FormControl('', Validators.pattern(this.pattern))
});
您只需添加2个验证即可添加2个同名控件。您可以插入以下验证器数组:
textForm = new FormGroup({
url: new FormControl('', [Validators.required, Validators.pattern(this.pattern)])
});
答案 2 :(得分:0)
实际上,您正在创建一个新的url控件,并且无法在单个表单中创建两个控件
this.formName.group({
title: [null,[Validators.required,Validators.pattern(this.pattern)]],
})