Validation by finding required fields - LWC (Salesforce)
How to use reportValidity?
필드들을 작성하고 save를 누르면 필드를 채우지 않은 것만 알림을 주고싶다!
어떻게 해야할까
<template>
<lightning-card title="Order a fruit">
<div class="slds-p-horizontal_small">
<lightning-combobox name="fruit"
label="Fruit"
class="required-field"
value={selectedValue}
options={fruitOptions}
required>
</lightning-combobox>
<lightning-input type="text"
label="order name"
class="required-field"
required>
</lightning-input>
<lightning-input type="text"
label="address"
class="required-field"
required>
</lightning-input>
<lightning-input type="text"
label="email"
class="required-field"
required>
</lightning-input>
<lightning-button
variant="brand"
label="Save"
onclick={handleSave}>
</lightning-button>
</div>
</lightning-card>
</template>
import {LightningElement} from 'lwc';
export default class Practice extends LightningElement {
selectedValue = '';
fruitOptions = [
{label: 'Apple', value: 'apple'},
{label: 'Banana', value: 'banana'},
{label: 'Orange', value: 'orange'},
{label: 'Grape', value: 'grape'},
];
handleSave() {
const requiredFields = this.template.querySelectorAll('.required-field');
let isValid = true;
requiredFields.forEach(field => {
if (!field.checkValidity()) {
field.reportValidity();
isValid = false;
}
});
if (isValid) {
alert('Selected Fruit: ' + this.selectedValue);
}
}
}
만약 부모창에서 자식창에 있는 필드들을 제어하려면?