1

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>);
}
8
  • You can search the internet for How to validate form with javascript - find a tutorial that suits your skill level. Commented Jun 21, 2022 at 12:48
  • Does this answer your question? How to validate form input with JavaScript Commented Jun 21, 2022 at 12:48
  • You could use <input type="url"> or <input pattern="^(ftp|http|https)://[^ "]+$"> Commented Jun 21, 2022 at 12:48
  • @ArtyomVancyan Unfortunately none of these options work. Commented Jun 21, 2022 at 12:55
  • What if onChange, you use if (/^(?:f|ht?)(?:t(?:ps?(?::(?:\/(?:\/\S*)?)?)?)?)?$/.test(value)) { setInput(value); } Commented Jun 21, 2022 at 13:45

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for the answer! But it doesn't work with my code. (the field does not allow entering data). Could you provide an example with my code? (in the condition there is a link to the sandbox)
I have added a message if the input is invalid: codesandbox.io/s/elastic-mountain-jdp8tp
Yes, I saw it, thanks. But in this case, incorrect results are still passed to the tag. And it is necessary for me that not correct results in a tag could not get. So that tags are formed only from valid results
What have you inputted that should not be a passed?
If the user enters an invalid result, then it should not be passed. That is, if the inscription "Invalid URL" is on, the result should not be transmitted. At the moment, the result is transmitted in any case - it is valid or not
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.