我有一个对象数组,它有切换值和日期字段,如果toogle是打开的,而date没有填充,我需要抛出一个错误消息。但在这里,它采用最后一个索引,并根据该索引值抛出验证消息,但在对象数组中,如果有任何对象的boolValue为true且date为null,则需要显示弹出消息。
TS:
let dateValue = false;
console.log(this.restrictionInfoDetails.value)
for (let i = 0; i < this.restrictionInfoDetails.value.length; i++) {
if (this.restrictionInfoDetails.value[i].boolValue == true) {
if (this.restrictionInfoDetails.value[i].datetime != null) {
dateValue = true;
} else {
dateValue = false;
}
}
} if (this.restrictionInfoDetails.value[0].boolValue == false && this.restrictionInfoDetails.value[1].boolValue == false && this.restrictionInfoDetails.value[2].boolValue == false) {
dateValue = true
}弹出窗口:
if ( !dateValue) {
this.notificationService.activate("Validation Message", errorMesage, "Ok", false).then(responseOK => {
if (responseOK) {
}
});
}数据:
this.restrictionInfoDetails.value = [
{boolValue: true, datetime: null},
{boolValue: true, datetime: null},
{boolValue: true, datetime: null}]发布于 2020-04-24 05:48:32
对数组的验证总是迭代数组并在条件为假时中断,或者使用辅助变量(例如,'valid',并使用'valid=valid && condition')
let valid=true;
this.restrictionInfoDetails.value.forEach(x=>{
valid=valid && (x.dateTime!=null || !x.boolValue)
})
console.log(valid)或
let valid=true;
for (let value of this.restrictionInfoDetails.value){
if (value.dateTime==null && value.boolValue)
{
valid=false;
break;
}
})
console.log(valid)要迭代,我们可以使用for..of或.forEach,请参阅the docs
无论如何,我想您询问的是FormArray的自定义验证器。表单数组中的customValidator就像另一个customValidator,只是一个函数(我喜欢放在同一个组件中)
myFormArray=new FormArray([],this.customValidator())
customValidator()
return (formArray:FormArray)=>{
if (formArray.value)
{
let valid=true;
formArray.value.forEach(x=>{
valid=valid && (x.dateTime!=null || !x.boolValue)
})
return !valid?{error:'You has an error':null}
}
}https://stackoverflow.com/questions/61387221
复制相似问题