[SalesForce] How to set Pattern properties of LWC lightning-input in js controller

I'm trying to set Pattern property from Javascript Controller as otherwise I have to provide some sort of valid pattern property (such as [\\w\\W\\D\\S]{0,} for instance which accepts pretty much anything). Currently I'm setting these via @track properties.

Problem here is, if this property is provided in the html template, as shown below, then that property can conflict with other properties such as min/max length resulting in broken validation behaviour.

    <template>
        <div class="textbox-gds">
            <lightning-input 
                oncommit={handleCommit} 
                type="text"
                pattern={htmlpattern}
                minlength={htmlminlength} 
                maxlength={htmlmaxlength}            
                name={Name} 
                value={value} 
                label={QuestionText} 
                onblur={handleBlur} 
            ></lightning-input>
        </div>
    </template>

What I really want to do is not have these present in the HTML template, and instead set them from controller is possible.

Below is a rough version of how I've been able to get access to the lightning-input element, but I'm struggling to figure out how (if this is even possible) to then set a value of the lightning-input, or even the underlying DOM.

renderedCallback(){

        if(!this.hasRendered){

            this.hasRendered = true;

            try{
                let elems = this.template.querySelectorAll('lightning-input');
                console.log(elems);
                elems.forEach(function (elem) {

                    let pattern = `[A-Za-z]{3}`;    

                    //elem.setPattern(pattern);
                    elem.setAttribute('pattern', pattern);

                });

            }catch(exception){
                console.log("EXCEPTION: ", exception);
            }

        }       

    }

Best Answer

Since the pattern attribute is a global property on lightning-input, you should be able to directly set it like so:

import { LightningElement } from 'lwc';

export default class App extends LightningElement {
    pattern = '[a-zA-Z]';

    renderedCallback() {
        const inputs = this.template.querySelectorAll('lightning-input');

        inputs.forEach(input => {
            // IMPORTANT BIT HERE
            input.pattern = this.pattern;
        });
    }
}

All global properties of a component can be get/set this way. See the access modifier in the Specification tab in the Component Reference.