Reputation: 67
For a training, I'am trying to check if the input value of this code base includes a "@" when onBlur
:
<form>
<input
type='text'
name='my_input'
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onBlur={(e) => checkEmail(e.target.value)}
></input>
<button>Save</button>
</form>
Therefore I added a function to display a <div>
below the form (or at least below the input field) if there is no "@" in the input, but without success: 🧐
function checkEmail(value) {
if (!value.includes('@')) {
<div>⚠️ Warning, there is no @, this is not a valid email address.</div>;
}
}
Knowing console.log(!value.includes('@'))
well return true. 😫
Any clue on how to get the <div>⚠️ Warning, there is no @, this is not a valid email address.</div>
shown below the form or input when invalid input?
Thanks in advance. 🙂
Upvotes: 2
Views: 591
Reputation: 1532
You are returning your JSX in the checkEmail
function, which isn't quite right. What you want to do instead is have a flag that indicates whether the warning JSX should be rendered, and setup a logic to do so if it is true. inputValue
being a state is really handy in this case, one small &&
operator should handle the rendering function.
<form> ... </form>
{ inputValue && !inputValue.includes('@') &&
(<div>⚠️ Warning, there is no @, this is not a valid email address.</div>) }
PS:
you can get rid of onBlur={(e) => checkEmail(e.target.value)}
and its handler method.
Upvotes: 1