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>);
}
<input type="url">or<input pattern="^(ftp|http|https)://[^ "]+$">onChange, you useif (/^(?:f|ht?)(?:t(?:ps?(?::(?:\/(?:\/\S*)?)?)?)?)?$/.test(value)) { setInput(value); }