Search code examples
javascriptreactjsmaterial-uiuitextfieldmasking

how to mask reactjs mui textfield


I have this textfield

<TextField
    error={!!errors.imageLink}
    helperText={errors.imageLink}
    FormHelperTextProps={{ variant: "standard" }}
    placeholder="Banner Link"
    size="small"
    className={classNames([
        classes.textField,
        classes.marginTextInput,
    ])}
    value={imageLink || ""}
    onChange={(e) => this.handleChange(e, "imageLink")}
    variant="outlined"
/>

i want to mask an url implementation, like user have to first type http or https, then after that :// auto applies then the rest of the link, how can I achieve this.


Solution

  • As no one answers this and very little is provided on internet about url masking, I haved made it work using react-text-mask it is far from perfect but it works posting for anyone in future who needs similar thing:

    <MaskedInput
                ref={ref => inputRef(ref ? ref.inputElement : null)}
                placeholderChar={' '}
                pipe={value => {
                    if(value[0] == "h" && value[1] == "t" && value[2] == "t" && value[3] == "p") {
                        if(value[4] && value[4] == "s") {
                            if (value[5] && value[5] != ":") {
                                return false;
                            } 
                            if (value[6] && value[6] != "/") {
                                return false;
                            } 
                            if (value[7] && value[7] != "/") {
                                return false;
                            }
    
                        } else {
                            if (value[4] && value[4] != ":") {
                                return false;
                            } 
                            if (value[5] && value[5] != "/") {
                                return false;
                            } 
                            if (value[6] && value[6] != "/") {
                                return false;
                            }
                        }
                        
                    } else if (
                        value.length === 1 && value[0] !== "h" || 
                        value.length === 2 && value[0] === "h" && value[1] !== "t" || 
                        value.length === 3 && value[0] === "h" && value[1] === "t" && value[2] !== "t" || 
                        value.length === 4 && value[0] === "h" && value[1] === "t" && value[2] === "t" && value[3] !== "p"
                    ) {
                        value = "https://" + value;
                    }
                
                    return value;
                }}
                mask={value => Array(value.length).fill(/[\d\D]/)}
                showMask={true}
                {...otherProps}
            />