For single input you can simple use input.validity.valid
this will return your validity.
Single Input
HTML:
<template>
<lightning-input
class="input"
label="Enter some text"
onblur={handleBlur}
>
</lightning-input>
</template>
JS:
handleBlur(event) {
var input = this.template.querySelector(".input");
console.log(input.validity.valid); //returns true
}
For multiple input:
You can use checkvalidity()
method to validate input again. Same method will validate your input and show message based on your latest data.
HTML
<template>
<lightning-input label="First name" placeholder="First name" required>
</lightning-input>
<lightning-input label="Last name" placeholder="Last name" required>
</lightning-input>
<lightning-button type="submit" label="Submit" onclick={handleClick}>
</lightning-button>
</template>
JS:
handleClick(evt) {
console.log('Current value of the input: ' + evt.target.value);
const allValid = [
...this.template.querySelectorAll('lightning-input'),
].reduce((validSoFar, inputCmp) => {
inputCmp.reportValidity();
return validSoFar && inputCmp.checkValidity();
}, true);
if (allValid) {
alert('All form entries look valid. Ready to submit!');
} else {
alert('Please update the invalid form entries and try again.');
}
}
Custom Validation
The component supports setCustomValidity()
from HTML5's Constraint Validation API. To set an error message, provide a quoted string to display. To reset the error message, set the message to an empty string ("")
HTML:
<template>
<lightning-input class="inputCmp" label="Enter your name:">
</lightning-input>
<lightning-button label="Register" onclick={register}> </lightning-button>
</template>
JS
register(event) {
var inputCmp = this.template.querySelector('.inputCmp');
var value = inputCmp.value;
// is input valid text?
if (value === 'John Doe') {
inputCmp.setCustomValidity('John Doe is already registered');
} else {
inputCmp.setCustomValidity(''); // if there was a custom error before, reset it
}
inputCmp.reportValidity(); // Tells lightning-input to show the error right away without needing interaction
}
Ref : https://developer.salesforce.com/docs/component-library/bundle/lightning-input/documentation
setCustomValidity
to make theselightning-input
elements invalid in the first place, this should work fine. Perhaps you are setting therequired
attribute instead? In that case, you should make sure the variable that sets therequired
attribute is being updated correctly.