| 1 |
import { useEffect, useState } from 'react'; |
| 2 |
import { Form, FormGroup, FormHelperText, TextInput, HelperText, HelperTextItem } from '@patternfly/react-core'; |
| 3 |
|
| 4 |
export const HelperTextStaticTextDynamicVariant: React.FunctionComponent = () => { |
| 5 |
const [value, setValue] = useState(''); |
| 6 |
const [inputValidation, setInputValidation] = useState({ |
| 7 |
ruleLength: 'indeterminate', |
| 8 |
ruleCharacterTypes: 'indeterminate' |
| 9 |
}); |
| 10 |
const { ruleLength, ruleCharacterTypes } = inputValidation; |
| 11 |
|
| 12 |
useEffect(() => { |
| 13 |
let lengthVariant = ruleLength; |
| 14 |
let typeVariant = ruleCharacterTypes; |
| 15 |
|
| 16 |
if (value === '') { |
| 17 |
setInputValidation({ |
| 18 |
ruleLength: 'indeterminate', |
| 19 |
ruleCharacterTypes: 'indeterminate' |
| 20 |
}); |
| 21 |
return; |
| 22 |
} |
| 23 |
|
| 24 |
if (!/\d/g.test(value)) { |
| 25 |
typeVariant = 'error'; |
| 26 |
} else { |
| 27 |
typeVariant = 'success'; |
| 28 |
} |
| 29 |
|
| 30 |
if (value.length < 5) { |
| 31 |
lengthVariant = 'error'; |
| 32 |
} else { |
| 33 |
lengthVariant = 'success'; |
| 34 |
} |
| 35 |
|
| 36 |
setInputValidation({ ruleLength: lengthVariant, ruleCharacterTypes: typeVariant }); |
| 37 |
}, [value, ruleLength, ruleCharacterTypes]); |
| 38 |
|
| 39 |
const handleInputChange = (_event, inputValue: string) => { |
| 40 |
setValue(inputValue); |
| 41 |
}; |
| 42 |
|
| 43 |
const filterValidations = () => Object.keys(inputValidation).filter((item) => inputValidation[item] !== 'success'); |
| 44 |
|
| 45 |
return ( |
| 46 |
<Form> |
| 47 |
<FormGroup label="Username" isRequired fieldId="login-input-helper-text3"> |
| 48 |
<TextInput |
| 49 |
isRequired |
| 50 |
type="text" |
| 51 |
id="login-input-helper-text3" |
| 52 |
name="login-input-helper-text3" |
| 53 |
onChange={handleInputChange} |
| 54 |
aria-describedby={filterValidations().join(' ')} |
| 55 |
aria-invalid={ruleCharacterTypes === 'error' || ruleLength === 'error'} |
| 56 |
value={value} |
| 57 |
/> |
| 58 |
<FormHelperText> |
| 59 |
<HelperText component="ul"> |
| 60 |
<HelperTextItem component="li" id="ruleLength" variant={ruleLength as any}> |
| 61 |
Must be at least 5 characters in length |
| 62 |
</HelperTextItem> |
| 63 |
<HelperTextItem component="li" id="ruleCharacterTypes" variant={ruleCharacterTypes as any}> |
| 64 |
Must include at least 1 number |
| 65 |
</HelperTextItem> |
| 66 |
</HelperText> |
| 67 |
</FormHelperText> |
| 68 |
</FormGroup> |
| 69 |
</Form> |
| 70 |
); |
| 71 |
}; |