2

Looking off of the documentation of lightning-input-address I see that when you mark it as required, everything but country is marked as required. Is there a way to pick and choose what you want as required in it? In the documentation it just states for validating required fields, but nothing else.

Was curious, because lets say I wanted to have Country and State(province) marked as required, but not City. Then how would I do that or if it is even possible with LWC.

2
  • 1
    I think you have to go for custom lightning-input fields for that. May 28, 2021 at 18:34
  • That's what I was thinking originally, but then I wouldn't be able to utilize the show-address-lookup feature lightning-input-address provides. May 28, 2021 at 18:40

1 Answer 1

3

This seems to be a bug to me, wherein only country is not marked required.

But if you want to mark only some fields required from the address component, you can remove the required attribute from the lightning-input-address component in html file and instead use setCustomValidityForField method in the JS. You can find the documentation of this method in the lightning-input-address specification

Below code sample shows how to validate only country and state fields

handleSubmit(event) {
    event.preventDefault();
    const address = this.template.querySelector('lightning-input-address');
    //Country Field Validation
    var country = address.country;
    if (!country) {
        address.setCustomValidityForField('Field is Required', 'country');
    } else {
        address.setCustomValidityForField("", 'country'); //Reset previously set message
    }

    //State Field Validation
    var province = address.province;
    if (!province) {
        address.setCustomValidityForField('Field is Required', 'province');
    } else {
        address.setCustomValidityForField("", 'province'); //Reset previously set message
    }
    address.reportValidity(); // Refreshes the component to show or remove error messages from UI
    const isValid = address.checkValidity(); //Check if the address is Valid and accordingly proceed.
    
}

The only drawback here is, the asterisk sign won't appear. You will have to fiddle with css a bit to achieve that.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .