Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度验证一对表单字段是否为空或两者都已填充_Javascript_Angular_Typescript_Validation - Fatal编程技术网

Javascript 角度验证一对表单字段是否为空或两者都已填充

Javascript 角度验证一对表单字段是否为空或两者都已填充,javascript,angular,typescript,validation,Javascript,Angular,Typescript,Validation,我创建了一个包含4到5个字段的学生表单。对于联系人号码,我有两个字段,国家代码和电话号码。如果用户只输入了两个字段中的一个,即输入了国家代码,但没有输入电话号码,我想抛出一个错误,反之亦然。但是,如果这两个字段都保留为空,那么它是有效的,因为这两个字段都是非必填字段。我不知道怎样才能做到这一点。请帮忙。提前谢谢 这是我的模板: <mat-form-field > <input matInput type="number" formControlName="countryCo

我创建了一个包含4到5个字段的学生表单。对于联系人号码,我有两个字段,国家代码和电话号码。如果用户只输入了两个字段中的一个,即输入了国家代码,但没有输入电话号码,我想抛出一个错误,反之亦然。但是,如果这两个字段都保留为空,那么它是有效的,因为这两个字段都是非必填字段。我不知道怎样才能做到这一点。请帮忙。提前谢谢

这是我的模板:

<mat-form-field >
<input matInput type="number"   formControlName="countryCode" placeholder="Country Code(+)" name="countryCode" class="form-control" id="countryCode">
</mat-form-field>
<mat-form-field >
<input matInput type="number" formControlName="phnNumber" placeholder="Phone Number" name="phnNumber" class="form-control" id="phnNumber">
</mat-form-field>

您可以创建一个自定义验证器,将其作为一个整体而不是单个控件放置在
FormGroup
上。您对
FormBuilder
的调用变为:

this.addForm=this.formBuilder.group({
学生姓名:['',验证器。必需],
phnnNumber:新表单控件(“”),
国家代码:新表单控件(“”),
},{验证器:myFormValidator});
然后创建一个验证器(在同一个文件中或其他地方并导出):

export const myFormValidator:ValidatorFn=(控件:FormGroup):ValidationErrors | null=>{
const phnNumber=control.get('phnNumber').value;
const countryCode=control.get('countryCode').value;
if(phnNumber&!countryCode | | countryCode&&!phnNumber){
返回{'phoneNumberError':true};
}否则{
返回null;
}
};

这样,自定义验证器就可以从整个组中获取它需要的内容,而不是需要单独验证控件。

这不会像预期的那样起作用,因为您需要比较控件的值,而不是在控件退出以提取值的情况下,感谢您捕捉到这一点!这也是我的建议,我投了赞成票。我对这种风格的唯一问题是将控件从表单组中取出的神奇字符串(不确定是否有更好的方法),但这就是生活。我还将该控件命名为formGroup。我还建议您将这两个控件放在它们自己的formgroupYep这是greatI'm getting error速记属性“myFormValidator”的作用域中不存在值。声明一个或提供一个初始值设定项。
this.addForm = this.formBuilder.group({

      studentName: ['', Validators.required],
      phnNumber: new FormControl(''),
      countryCode: new FormControl(''),
    });