1

I am building LWC component and have a few comboboxes that some of them are required.

<lightning-combobox
        required="true"
        label="My combo"
        options={options}
        value={myValue}
        onchange={onChangeOptions}>

When the user clicks submit I am executing inputField.reportValidity(); for all components

Then if the required comboboxes are empty I get error messages:

enter image description here

All this is ok.

Now, I have also a reset button which should reset all comboboxes to an empty state.

Problem:

When I click on the reset button I want also that all the red errors would disappear - like the page has just started.

I am clearing the combobox's value to null, it does not help

I tried also:

this.template.querySelectorAll('lightning-combobox').forEach(element => {
    element.value = null;
}

and it does not help

And tried:

this.myValue = null;

and it also does not help

Question:

Is there a way to make the red error and the red square surrounding the element disapear?

Thanks

4
  • 1
    Have you tried with inputField.setCustomValidity('')
    – devforce
    Jan 13 at 10:41
  • As also stated by dev force , setting customvalidtity to '' should resolve your issue
    – elijah
    Jan 13 at 10:54
  • @devforce That doesn't work. Because it is not a custom message to begin with, you cannot clear it that way. I tried. I did get it to work via two other ways, though.
    – sfdcfox
    Jan 13 at 12:51
  • as @sfdcfox said - this is not a custom validity so it does not work 2 days ago
1

You have two options available to you.

Option 1

Set the field to a legal value, then wait a tick, use reportValidity, then set it back to null.

resetField(event) {
  this.myValue = '1'
  setTimeout(() => (this.template.querySelector('lightning-combobox').reportValidity(), this.myValue = null))
}

This creates a brief flicker in the field(s) as they are set to a value, then back to null, but the layout remains undisturbed.

Option 2

Hide the field temporarily, then restore it:

resetField(event) {
  // set fields to null here, then...
  this.showForm = false;
  setTimeout(() => this.showForm = true)
}

This causes a brief flicker as the elements are taken out of the DOM and put back in again, but will leave the form fully reset. You can put the if:true demonstrated above on the form itself, rather than each individual field. This would be a lot easier to manage.

I have confirmed that using setCustomValidity by itself is insufficient to clear the error state, because it was not set by setCustomValidity initially.

I have created a custom component demonstrating both valid techniques.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.