Angular表单条件必填:weight_purchase_price有值时设weight等为必填
Angular表单动态必填验证实现
需求:当weight_purchase_price字段有值时,将weight和weight_unit_price_measurement_type字段设为必填项;当weight_purchase_price为空时,这两个字段无需必填。
实现方案
通过监听weight_purchase_price的输入变化,动态为目标控件添加或移除Validators.required验证器即可实现,具体代码修改如下:
修改后的完整代码
initializePricingForm(): void { this.pricingForm = new FormGroup({ price: new FormGroup({ selling_type: new FormControl('', Validators.compose([ Validators.required ])), unit: new FormControl('pence'), unit_price: new FormControl(''), purchase_price: new FormControl(''), pack_purchase_price: new FormControl(''), weight_purchase_price: new FormControl(''), weight: new FormControl(''), weight_unit_price_measurement_type: new FormControl(''), }), currency: new FormControl('GBP'), }); // 获取需要操作的控件引用 const weightPurchasePriceCtrl = this.pricingForm.get('price.weight_purchase_price'); const weightCtrl = this.pricingForm.get('price.weight'); const weightUnitCtrl = this.pricingForm.get('price.weight_unit_price_measurement_type'); // 监听weight_purchase_price的变化,动态切换验证规则 this.subs.sink = weightPurchasePriceCtrl?.valueChanges.subscribe((value) => { const hasValidValue = !!value?.trim(); // 为weight字段设置/移除必填验证 weightCtrl?.setValidators(hasValidValue ? Validators.required : null); // 为weight_unit_price_measurement_type字段设置/移除必填验证 weightUnitCtrl?.setValidators(hasValidValue ? Validators.required : null); // 更新控件验证状态,emitEvent设为false避免触发表单全局valueChanges循环 weightCtrl?.updateValueAndValidity({ emitEvent: false }); weightUnitCtrl?.updateValueAndValidity({ emitEvent: false }); }); this.validationMessege(); this.subs.sink = this.pricingForm.valueChanges.subscribe(() => { this.emitFormData(); }); }
关键逻辑说明
!!value?.trim():判断weight_purchase_price是否存在有效输入(排除纯空格的无效值)setValidators:根据输入状态动态添加或移除必填验证器,无值时传入null清除验证规则updateValueAndValidity({ emitEvent: false }):更新控件的验证状态,同时阻止触发表单全局的valueChanges,避免重复执行emitFormData
内容的提问来源于stack exchange,提问作者Shawn
相关产品推荐
相关产品推荐

