I do not understand why my code does not display the entry I want in my form. I want to display an invalid entry with a danger message when my user enters a phone number already in use.
I check the user input and check the Boolean display cases.
This is my booleans when I enter a phone number already used:
phoneAlreadyUsed: true
phoneCharged: false
phoneTouched: true
phoneValid: true
My code has detected that it phone number is already in use, so the boolean "phoneAlreadyUsed" is true.
This the code of my content:
<FormGroup className="form-group">
<Label>Phone *</Label>
{userVerification.phoneTouched === false && userVerification.phoneAlreadyUsed === false && (
<Input
type="text"
name="phone"
className="form-control"
value={user ? user.phone : ''}
placeholder={'Enter your phone number'}
onChange={handleChange}
/>
)}
{userVerification.phoneValid === true && userVerification.phoneAlreadyUsed === false && (
<Input
type="text"
name="phone"
className="form-control is-valid"
value={user ? user.phone : ''}
placeholder={'Enter your phone number'}
onChange={handleChange}
/>
)}
{((userVerification.phoneValid === false && userVerification.phoneTouched === true) ||
userVerification.phoneAlreadyUsed === true) && (
<Input
type="text"
name="phone"
className="form-control is-invalid"
value={user ? user.phone : ''}
placeholder={'Enter your phone number'}
onChange={handleChange}
/>
)}
{userVerification.phoneAlreadyUsed === true && (
<div class="invalid-feedback">Sorry, this phone number's taken. Try another?</div>
)}
</FormGroup>
My code display the second input (valid) without the message in "invalid-feedback". I don't understand why... Could you help me please?
You are unnecessarily duplicating a lot of code. All that is different in your cases is the className
prop of the Input
component. You can easily construct it:
//in render
const {phoneTouched, phoneValid, phoneAlreadyUsed} = userVerification;
let className = 'form-control';
if (phoneTouched) {
const valid = phoneValid && !phoneAlreadyUsed;
className += valid ? 'is-valid' : 'is-invalid';
}
return (
<FormGroup className="form-group">
<Label>Phone *</Label>
<Input
type="text"
name="phone"
className={className}
value={user ? user.phone : ''}
placeholder={'Enter your phone number'}
onChange={handleChange}
/>
{phoneAlreadyUsed && (
<div class="invalid-feedback">
Sorry, this phone number's taken. Try another?
</div>
)}
</FormGroup>
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.