Suppose that you have lighting-input field in your lighting component where you want to allow only number type input , well there are several ways to achieve this goal. You can write come complex JavaScript code and add validation on that input field , or there are many ways you will find.
Here in this blog we will see a simple and easiest way to restrict lightning-input field in lightning component , this solution can also be used with simple HTML input tag.
Solution :
Create lighting-input field with type=”number”
<lightning-input label="Enter Number" type="number" class="validateInput"></lightning-input>
now inside CSS file use className:invalid property , that will automatically handle input field based on type of input format .
Here I our case we are having class name as validateInput.
.validateInput :invalid {
background-color: #ffe6e6;
}
and this is how simple it is to restrict input field in salesforce lighting component , notice that here we used input type=”number” if you do the same with email or tel type input then this trick can be applied their also.
Thank you…..
Corrections to the code above
- The CSS line
background:colur:red;has a typo and is not valid. The correct property isbackground-color. The post now uses a corrected line. - Setting
type="number"already blocks letters in most browsers, but not every character such as e or +, so extra checks help. - Styling an inner
:invalidstate from the component CSS is not reliable inside the lightning-input shadow DOM. The validation attributes below are the dependable option.
Use the built-in validation
<lightning-input
type="number"
label="Enter Number"
min="0"
step="1"
message-when-range-underflow="Enter 0 or more"
message-when-step-mismatch="Enter a whole number"
onchange={handleChange}>
</lightning-input>handleChange(event) {
event.target.reportValidity();
}reportValidity() shows the error message under the field when the value breaks min, step or another rule.
Block non-digit keys
blockNonDigits(event) {
if (event.key.length === 1 && !/[0-9]/.test(event.key)) {
event.preventDefault();
}
}Add onkeydown={blockNonDigits} to the lightning-input. Keys such as Backspace and the arrows have a longer key name, so they still work. For a text input, you can also use the attributes pattern="[0-9]*" and message-when-pattern-mismatch.
FAQ
Does this stop pasted text?
The key check does not. The validation attributes still flag a wrong pasted value.
Does it work for phone numbers?
Use type tel with a pattern, because phone numbers can start with zero or a plus sign.