formik#ErrorMessage TypeScript Examples
The following examples show how to use
formik#ErrorMessage.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FieldText.tsx From panvala with Apache License 2.0 | 6 votes |
FieldText = props => {
return (
<>
{props.label && (<Label required={props.required}>{props.label}</Label>)}
<div className="red tl pt2">
<ErrorMessage name={props.name} component="span" />
</div>
<Input type={props.type || 'text'} {...props} />
</>
);
}
Example #2
Source File: index.tsx From advanced-formik-validations-with-yup with MIT License | 6 votes |
FormikField: React.FC<FormikFieldProps> = ({ name, label, type = "text", required = false}) => {
return (
<div className="FormikField">
<Field
required={required}
autoComplete="off"
as={TextField}
label={label}
name={name}
fullWidth
type={type}
helperText={<ErrorMessage name={name} />}
/>
</div>
);
}
Example #3
Source File: index.tsx From advanced-formik-validations-with-yup with MIT License | 6 votes |
FormikSelect: React.FC<FormikSelectProps> = ({ name, items, label, required = false }) => {
return (
<div className="FormikSelect">
<Field
name={name}
as={MaterialUISelectField}
label={label}
errorString={<ErrorMessage name={name} />}
required={required}
>
{items.map(item => (
<MenuItem key={item.value} value={item.value}>
{item.label}
</MenuItem>
))}
</Field>
</div>
);
}
Example #4
Source File: index.tsx From krmanga with MIT License | 6 votes |
function Input({ field, form, iconName, cancel, ...rest }: IProps) {
const onPress = () => {
if (typeof cancel === "function") {
cancel(form, field);
}
};
return (
<View style={styles.container}>
<View style={styles.inputView}>
<Icon name={iconName} color={Color.night} size={20} />
<TextInput
{...field}
{...rest}
style={styles.input}
onChangeText={form.handleChange(field.name)}
onBlur={form.handleBlur(field.name)}
/>
<Touchable onPress={onPress}>
<Icon name={"icon-chacha"} color={Color.night} size={20} />
</Touchable>
<ErrorMessage
name={field.name}
component={Text}
render={
msg => {
return (
<Text style={styles.error}>{msg}</Text>
);
}
}
/>
</View>
</View>
);
}
Example #5
Source File: formComponents.tsx From Account-Manager with MIT License | 6 votes |
renderFormError = ({
className,
hideErrorText,
name,
}: {
className?: string;
hideErrorText?: boolean;
name: string;
}): ReactNode => (
<span className={clsx('FormFieldComponent__error-message', {...bemify(className, '__error-message')})}>
{hideErrorText ? null : <ErrorMessage name={name} />}
</span>
)
Example #6
Source File: add-training-goal-task.form.component.tsx From MyWay-client with MIT License | 6 votes |
export default function AddTrainingGoalTaskForm({
dogId,
goalId,
}: {
dogId: number;
goalId: number;
}) {
return (
<Formik
initialValues={{ description: "" }}
onSubmit={(values, actions) => {
axios.post(`/api/dogs/${dogId}/training-goals/${goalId}/tasks`, {
...values,
});
}}
>
<Form>
<Field name="description" placeholder="description" />
<ErrorMessage name="description" />
<button type="submit">Add Task</button>
</Form>
</Formik>
);
}
Example #7
Source File: add-training-goal.form.component.tsx From MyWay-client with MIT License | 6 votes |
export default function AddTrainingGoalForm({ dogId }: { dogId: number }) {
return (
<Formik
initialValues={{ title: "" }}
onSubmit={(values, actions) => {
axios.post(`/api/dogs/${dogId}/training-goals`, { ...values });
}}
>
<Form>
<Field name="title" placeholder="Title" />
<ErrorMessage name="title" />
<button type="submit">Add New Goal</button>
</Form>
</Formik>
);
}
Example #8
Source File: FormError.tsx From panvala with Apache License 2.0 | 5 votes |
FormError = props => {
const classes = `red tl ${props.className}`;
return (
<div className={classes}>
<ErrorMessage name={props.name} />
</div>
);
}
Example #9
Source File: SelectField.tsx From amplication with Apache License 2.0 | 5 votes |
SelectField = ({
label,
name,
options,
isMulti,
isClearable,
disabled,
}: Props) => {
const [field, meta, { setValue }] = useField<string | string[]>(name);
const handleChange = useCallback(
(selected) => {
// React Select emits values instead of event onChange
if (!selected) {
setValue([]);
} else {
const values = isMulti
? selected.map((option: OptionItem) => option.value)
: selected.value;
setValue(values);
}
},
[setValue, isMulti]
);
const value = useMemo(() => {
const values = field.value || [];
return isMulti
? options.filter((option) => values.includes(option.value))
: options.find((option) => option.value === values);
}, [field, isMulti, options]);
return (
<div
className={classNames("select-field", {
"select-field--has-error": meta.error,
})}
>
<label className={LABEL_CLASS}>
<span className={LABEL_VALUE_CLASS}>{label}</span>
<Select
components={{ Option: CustomOption }}
className="select-field__container"
classNamePrefix="select-field"
{...field}
isMulti={isMulti}
isClearable={isClearable}
// @ts-ignore
value={value}
onChange={handleChange}
options={options}
isDisabled={disabled}
/>
</label>
<ErrorMessage name={name} component="div" className="text-input__error" />
</div>
);
}
Example #10
Source File: FieldError.tsx From netify with BSD 2-Clause "Simplified" License | 5 votes |
FieldError = memo<FieldErrorProps>(function FieldError({name}) {
return <ErrorMessage component='p' className={styles.root} name={name} />;
})
Example #11
Source File: training-goal-task.form.component.tsx From MyWay-client with MIT License | 5 votes |
export default function TrainingGoalTaskForm({
dogId,
goalId,
taskId,
}: {
dogId: number;
goalId: number;
taskId: number;
}) {
const [task, setTask] = useState<TrainingGoalTaskDto | null>(null);
const { dogsStore } = useStores();
useEffect(() => {
dogsStore
.findOneTask(dogId, goalId, taskId)
.then((task: TrainingGoalTaskDto) => setTask(task));
}, [dogId, goalId, taskId, dogsStore]);
if (!task) {
return <Spinner />;
}
return (
<Formik
initialValues={{
description: task.description,
startDate: convertDateForDatePicker(new Date(task.startingTraining)),
endDate: convertDateForDatePicker(new Date(task.endingTraining)),
}}
onSubmit={(values, actions) => {
axios.put(
`/api/dogs/${dogId}/training-goals/${goalId}/tasks/${taskId}`,
{ ...values }
);
}}
>
<Form>
<Field name="description" placeholder="description" />
<ErrorMessage name="description" />
<Field name="startDate" type="date" />
<ErrorMessage name="startDate" />
<Field name="endDate" type="date" />
<ErrorMessage name="endDate" />
<button type="submit">Save</button>
</Form>
</Formik>
);
}
Example #12
Source File: training-goals.form.component.tsx From MyWay-client with MIT License | 5 votes |
export default function TrainingGoalsForm({ dogId }: { dogId: number }) {
const [trainingGoals, setTrainingGoals] = useState<TrainingGoalDto[] | null>(
null
);
const { dogsStore } = useStores();
useEffect(() => {
dogsStore
.findAllTrainingGoals(dogId)
.then((trainingGoals: TrainingGoalDto[]) =>
setTrainingGoals(trainingGoals)
);
}, [dogId, dogsStore]);
if (!trainingGoals) {
return <Spinner />;
}
if (!trainingGoals.length) {
return (
<>
<p>No goals have been set.</p>
<AddTrainingGoalForm dogId={dogId} />
</>
);
}
return (
<>
<AddTrainingGoalForm dogId={dogId} />
<ul>
{trainingGoals.map((goal) => (
<li key={goal.id}>
<Formik
initialValues={{ title: goal.title }}
onSubmit={(values, actions) => {
axios.patch(`/api/dogs/${dogId}/training-goals/${goal.id}`, {
...values,
});
}}
>
<>
<Form>
<Field name="title" />
<ErrorMessage name="title" />
<button type="submit">Save</button>
</Form>
<AddTrainingGoalTaskForm dogId={dogId} goalId={goal.id} />
<ul>
{goal.tasks.map((task) => (
<li key={task.id}>
<TrainingGoalTaskForm
dogId={dogId}
goalId={goal.id}
taskId={task.id}
/>
</li>
))}
</ul>
</>
</Formik>
</li>
))}
</ul>
</>
);
}
Example #13
Source File: MetricAssignmentsPanel.tsx From abacus with GNU General Public License v2.0 | 4 votes |
/** * Renders the assigned metric information of an experiment in a panel component. * * @param experiment - The experiment with the metric assignment information. * @param experimentReloadRef - Trigger a reload of the experiment. * @param metrics - The metrics to look up (aka resolve) the metric IDs of the * experiment's metric assignments. */ function MetricAssignmentsPanel({ experiment, experimentReloadRef, metrics, }: { experiment: ExperimentFull experimentReloadRef: React.MutableRefObject<() => void> metrics: Metric[] }): JSX.Element { const classes = useStyles() const resolvedMetricAssignments = useMemo( () => resolveMetricAssignments(MetricAssignments.sort(experiment.metricAssignments), metrics), [experiment, metrics], ) // TODO: Normalize this higher up const indexedMetrics = indexMetrics(metrics) // Assign Metric Modal const { enqueueSnackbar } = useSnackbar() const canAssignMetric = experiment.status !== Status.Staging const [isAssigningMetric, setIsAssigningMetric] = useState<boolean>(false) const assignMetricInitialAssignMetric = { metricId: '', attributionWindowSeconds: '', changeExpected: false, isPrimary: false, minDifference: '', } const onAssignMetric = () => setIsAssigningMetric(true) const onCancelAssignMetric = () => { setIsAssigningMetric(false) } const onSubmitAssignMetric = async (formData: { metricAssignment: typeof assignMetricInitialAssignMetric }) => { try { await ExperimentsApi.assignMetric(experiment, formData.metricAssignment as unknown as MetricAssignmentNew) enqueueSnackbar('Metric Assigned Successfully!', { variant: 'success' }) experimentReloadRef.current() setIsAssigningMetric(false) } catch (e) /* istanbul ignore next; Shouldn't happen */ { console.error(e) enqueueSnackbar( `Oops! Something went wrong while trying to assign a metric to your experiment. ${serverErrorMessage(e)}`, { variant: 'error', }, ) } } return ( <Paper> <Toolbar> <Typography className={classes.title} color='textPrimary' variant='h3'> Metrics </Typography> <Tooltip title={canAssignMetric ? '' : 'Use "Edit in Wizard" for staging experiments.'}> <div> <Button onClick={onAssignMetric} variant='outlined' disabled={!canAssignMetric}> <Add /> Assign Metric </Button> </div> </Tooltip> </Toolbar> <Table className={classes.metricsTable}> <TableHead> <TableRow> <TableCell component='th' variant='head'> Name </TableCell> <TableCell component='th' variant='head' className={classes.smallColumn}> Attribution Window </TableCell> <TableCell component='th' variant='head' className={classes.smallColumn}> Changes Expected </TableCell> <TableCell component='th' variant='head' className={classes.smallColumn}> Minimum Difference </TableCell> </TableRow> </TableHead> <TableBody> {resolvedMetricAssignments.map((resolvedMetricAssignment) => ( <TableRow key={resolvedMetricAssignment.metricAssignmentId}> <TableCell> <Tooltip title={resolvedMetricAssignment.metric.name}> <strong className={clsx(classes.monospace, classes.metricName)}> {resolvedMetricAssignment.metric.name} </strong> </Tooltip> <br /> <small className={classes.monospace}>{resolvedMetricAssignment.metric.description}</small> <br /> {resolvedMetricAssignment.isPrimary && <Attribute name='primary' />} </TableCell> <TableCell className={classes.monospace}> {AttributionWindowSecondsToHuman[resolvedMetricAssignment.attributionWindowSeconds]} </TableCell> <TableCell className={classes.monospace}> {formatBoolean(resolvedMetricAssignment.changeExpected)} </TableCell> <TableCell className={classes.monospace}> <MetricValue value={resolvedMetricAssignment.minDifference} metricParameterType={resolvedMetricAssignment.metric.parameterType} isDifference={true} /> </TableCell> </TableRow> ))} </TableBody> </Table> <Dialog open={isAssigningMetric} aria-labelledby='assign-metric-form-dialog-title'> <DialogTitle id='assign-metric-form-dialog-title'>Assign Metric</DialogTitle> <Formik initialValues={{ metricAssignment: assignMetricInitialAssignMetric }} onSubmit={onSubmitAssignMetric} validationSchema={yup.object({ metricAssignment: metricAssignmentNewSchema })} > {(formikProps) => { const metricAssignmentsError = formikProps.touched.metricAssignment?.metricId && formikProps.errors.metricAssignment?.metricId const onMetricChange = (_event: unknown, metric: Metric | null) => formikProps.setFieldValue('metricAssignment.metricId', metric?.metricId) return ( <form onSubmit={formikProps.handleSubmit} noValidate> <DialogContent> <div className={classes.row}> <FormControl component='fieldset' fullWidth> <FormLabel required className={classes.label} htmlFor={`metricAssignment.metricId`}> Metric </FormLabel> <MetricAutocomplete id={`metricAssignment.metricId`} value={indexedMetrics[Number(formikProps.values.metricAssignment.metricId)] ?? null} onChange={onMetricChange} options={Object.values(indexedMetrics)} error={metricAssignmentsError} fullWidth /> {formikProps.errors.metricAssignment?.metricId && ( <FormHelperText error={true}> <ErrorMessage name={`metricAssignment.metricId`} /> </FormHelperText> )} </FormControl> </div> <div className={classes.row}> <FormControl component='fieldset' fullWidth> <FormLabel required className={classes.label} id={`metricAssignment.attributionWindowSeconds-label`} > Attribution Window </FormLabel> <Field component={Select} name={`metricAssignment.attributionWindowSeconds`} labelId={`metricAssignment.attributionWindowSeconds-label`} id={`metricAssignment.attributionWindowSeconds`} variant='outlined' error={ // istanbul ignore next; trivial, not-critical, pain to test. !!formikProps.errors.metricAssignment?.attributionWindowSeconds && !!formikProps.touched.metricAssignment?.attributionWindowSeconds } displayEmpty > <MenuItem value=''>-</MenuItem> {Object.entries(AttributionWindowSecondsToHuman).map( ([attributionWindowSeconds, attributionWindowSecondsHuman]) => ( <MenuItem value={attributionWindowSeconds} key={attributionWindowSeconds}> {attributionWindowSecondsHuman} </MenuItem> ), )} </Field> {formikProps.errors.metricAssignment?.attributionWindowSeconds && ( <FormHelperText error={true}> <ErrorMessage name={`metricAssignment.attributionWindowSeconds`} /> </FormHelperText> )} </FormControl> </div> <div className={classes.row}> <FormControl component='fieldset' fullWidth> <FormLabel required className={classes.label}> Change Expected </FormLabel> <Field component={Switch} label='Change Expected' name={`metricAssignment.changeExpected`} id={`metricAssignment.changeExpected`} inputProps={{ 'aria-label': 'Change Expected', }} variant='outlined' type='checkbox' /> </FormControl> </div> <div className={classes.row}> <FormControl component='fieldset' fullWidth> <FormLabel required className={classes.label} id={`metricAssignment.minDifference-label`}> Minimum Difference </FormLabel> <MetricDifferenceField name={`metricAssignment.minDifference`} id={`metricAssignment.minDifference`} metricParameterType={ (formikProps.values.metricAssignment.metricId && indexedMetrics[formikProps.values.metricAssignment.metricId as unknown as number] .parameterType) || MetricParameterType.Conversion } /> </FormControl> </div> </DialogContent> <DialogActions> <Button onClick={onCancelAssignMetric} color='primary'> Cancel </Button> <LoadingButtonContainer isLoading={formikProps.isSubmitting}> <Button type='submit' variant='contained' color='secondary' disabled={formikProps.isSubmitting || !formikProps.isValid} > Assign </Button> </LoadingButtonContainer> </DialogActions> </form> ) }} </Formik> </Dialog> </Paper> ) }
Example #14
Source File: CustomIdField.tsx From firecms with MIT License | 4 votes |
export function CustomIdField<M, UserType>
({ schema, status, onChange, error, entity }: {
schema: EntitySchema<M>,
status: EntityStatus,
onChange: Function,
error: boolean,
entity: Entity<M> | undefined
}) {
const classes = formStyles();
const disabled = status === "existing" || !schema.customId;
const idSetAutomatically = status !== "existing" && !schema.customId;
const hasEnumValues = typeof schema.customId === "object";
const snackbarContext = useSnackbarController();
const { copy } = useClipboard({
onSuccess: (text) => snackbarContext.open({
type: "success",
message: `Copied ${text}`
})
});
const appConfig: FireCMSContext<UserType> | undefined = useFireCMSContext();
const inputProps = {
className: classes.input,
endAdornment: entity
? (
<InputAdornment position="end">
<IconButton onClick={(e) => copy(entity.id)}
aria-label="copy-id"
size="large">
<Tooltip title={"Copy"}>
<svg
className={"MuiSvgIcon-root MuiSvgIcon-fontSizeSmall"}
fill={"currentColor"}
width="20" height="20" viewBox="0 0 24 24">
<path
d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
</svg>
</Tooltip>
</IconButton>
{appConfig?.entityLinkBuilder &&
<a href={appConfig.entityLinkBuilder({ entity })}
rel="noopener noreferrer"
target="_blank">
<IconButton onClick={(e) => e.stopPropagation()}
aria-label="go-to-datasource" size="large">
<Tooltip title={"Open in the console"}>
<OpenInNewIcon fontSize={"small"}/>
</Tooltip>
</IconButton>
</a>}
</InputAdornment>
)
: undefined
};
const fieldProps: any = {
label: idSetAutomatically ? "ID is set automatically" : "ID",
disabled: disabled,
name: "id",
type: null,
value: entity && status === "existing" ? entity.id : undefined,
variant: "filled"
};
return (
<FormControl fullWidth
error={error}
{...fieldProps}
key={"custom-id-field"}>
{hasEnumValues && schema.customId &&
<>
<InputLabel id={"id-label"}>{fieldProps.label}</InputLabel>
<MuiSelect
labelId={"id-label"}
className={classes.select}
error={error}
{...fieldProps}
onChange={(event: any) => onChange(event.target.value)}>
{Object.entries(schema.customId).map(([key, label]) =>
<MenuItem
key={`custom-id-item-${key}`}
value={key}>
{`${key} - ${label}`}
</MenuItem>)}
</MuiSelect>
</>}
{!hasEnumValues &&
<MuiTextField {...fieldProps}
error={error}
InputProps={inputProps}
helperText={schema.customId === "optional" ? "Leave this blank to autogenerate an ID" : "ID of the new document"}
onChange={(event) => {
let value = event.target.value;
if (value) value = value.trim();
return onChange(value.length ? value : undefined);
}}/>}
<ErrorMessage name={"id"}
component="div">
{(_) => "You need to specify an ID"}
</ErrorMessage>
</FormControl>
);
}
Example #15
Source File: SignupForm.tsx From querybook with Apache License 2.0 | 4 votes |
SignupForm: React.FunctionComponent<ISignupFormProps> = ({
onSuccessLogin,
}) => {
const [errorMessage, setErrorMessage] = React.useState<string>(null);
return (
<Formik
validate={validatePassword}
validationSchema={signupSchema}
initialValues={{
username: '',
password: '',
repeatPassword: '',
email: '',
}}
onSubmit={({ username, password, email }) =>
UserResource.signup(
username,
password,
email
).then(onSuccessLogin, (error) =>
setErrorMessage(String(error))
)
}
>
{({ handleSubmit, isSubmitting, isValid }) => {
const usernameField = (
<SimpleField type="input" name="username" />
);
const emailField = (
<FormField
label="Email"
error={() => <ErrorMessage name="email" />}
>
<Field type="email" name="email" />
</FormField>
);
const passwordField = (
<SimpleField
type="input"
name="password"
inputType="password"
/>
);
const repeatPasswordField = (
<SimpleField
type="input"
name="repeatPassword"
inputType="password"
label="Repeat Password"
/>
);
const errorMessageDOM = errorMessage && (
<Message message={errorMessage} type="error" />
);
const signupButton = (
<Button
onClick={() => handleSubmit()}
title="Signup"
disabled={isSubmitting || !isValid}
/>
);
return (
<FormWrapper className="SignupForm" minLabelWidth="150px">
<Form>
{usernameField}
{emailField}
{passwordField}
{repeatPasswordField}
{errorMessageDOM}
<br />
<div className="center-align">{signupButton}</div>
</Form>
</FormWrapper>
);
}}
</Formik>
);
}