0

I am using the Lightning-input field which is required field.

When I leave the field empty it shows a validation error. But the error stays there till I give some input and click outside

Is there any way to remove the validation error border and Error message as soon as I Focus Into the Input field? enter image description here

2
  • I don't there is any standard way to resolve this. You may create HTML input fields instead of standard lightning field.
    – MIX DML
    Sep 17, 2021 at 18:12
  • Yes..i know but that will complicate the other processes like Fields validations etc.
    – Agnibha
    Sep 17, 2021 at 18:41

2 Answers 2

1

In order to remove the error message and border as soon as an user fills the required field you can handle the keyup event calling the reportValidity() method on lightning-input element.
Documentation (emphasis mine):

Displays the error messages and returns false if the input is invalid.
If the input is valid, reportValidity() clears displayed error messages and returns true.

HTML:

<lightning-input required type="text" label="Enter some text" onkeyup={handleKeyUp}></lightning-input>

JS:

handleKeyUp(event) {
    event.currentTarget.reportValidity();
}
0

**This is a solution that uses a workaround. Please assess risks before using.

You'll need to remove the slds-has-error class explicitly using javascript.

There are 2 parts to this because removing the slds-has-error only removes the styles related to an error, not the elements related to it.

1st - Removing the red border and slds-has-error

HTML:

<lightning-input class="thisInput" type="text" label="Enter some text" onfocus={handleFocus} required ></lightning-input>

JS:

handleFocus(event) {
    event.target.className = event.target.className.replace('slds-has-error', '');
}

Using QuerySelector:

handleFocus(event) {
    let input = this.template.querySelector('.thisInput');
    input.className = input.className.replace('slds-has-error', '');
}

2nd - Removing the validation message from the view

You'll need to override the slds-form-element__help css only in the event that it doesn't have its corresponding slds-has-error. You can achieve that by importing a css file from the static resource (overriding inside your LWC will not allow this).

inputLwc.js:

import { LightningElement } from 'lwc';
import override from '@salesforce/resourceUrl/override.css';

export default class InputLwc extends LightningElement {
    overrideCss = override;

    connectedCallback() {
        loadStyle(this, this.overrideCss)
        .then(() => {
            console.log('overrideCss loaded');
        });
    }
}

override.css:

.thisInput:not(.slds-has-error) .slds-form-element__help {
     display: none;
}

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.