Home > Net >  Add URL Validation to TagsInput
Add URL Validation to TagsInput

Time:06-22

I have an input field where the user is required to enter a link (URL). However, at the moment this field does not have any validation, so the user can enter any nonsense.

So far, I don't need any complex regex.

regex = = /^(ftp|http|https)://[^ "] $/; is enough for me

However, my problem is that I don't know how to put this expression in my code. I would like that if the entered data does not pass validation, a notification pops up to the user about this.

Thus, at the moment, the input field accepts any string, but I would like it to accept only the URL, and if it is not a URL, then give a small message about it

Please tell me how can I get this result.

export default function TagsInputLink(props) {
    const tags = props.tags
    const setTags = props.setTags
    const [input, setInput] = React.useState('');

    const onChange = (e) => {
        const { value } = e.target;
        setInput(value);
    };

    const onKeyDown = (e) => {
        const { key } = e;
        const trimmedInput = input.trim();

        if ((key === 'Enter') && trimmedInput.length && !tags.includes(trimmedInput)) {
            e.preventDefault();
            setTags(prevState => [...prevState, trimmedInput]);
            setInput('');
        }
    };

    const deleteTag = (index) => {
        setTags(prevState => prevState.filter((tag, i) => i !== index))
    }

    return (
        <div className={classes.container}>
            {tags.map((tag, index) => <div className={classes.tag}>
                <ClearIcon className={classes.del} fontSize="big" onClick={() => deleteTag(index)} />
                {tag}
            </div>
            )}
            <input
                className={classes.input}
                value={input}
                placeholder={props.inputPlaceholder}
                onKeyDown={onKeyDown}
                onChange={onChange}
            />
        </div>);
}

CodePudding user response:

You could implement it only with onChange holding the validity state like below.

const {useState, useMemo} = React;

function URLInput() {
  const [isValid, setIsValid] = useState(true);
  
  const style = useMemo(() => {
    return {border: `2px solid ${isValid ? "green" : "red"}`};
  }, [isValid]);
  
  const onChange = (e) => {
    if (e.target.value) {
      setIsValid(() => /^(ftp|https?):\/\/[^ "] $/.test(e.target.value));
    } else {
      setIsValid(true);
    }
  }

  return <input onChange={onChange} style={style}/>;
}

function App() {
  return <URLInput/>;
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

  • Related