formik#ErrorMessage JavaScript 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: TextDemo.js From real-frontend with GNU General Public License v3.0 | 6 votes |
TextDemo = ({
theme,
field: {
value,
name,
},
form,
placeholder,
multiline = false,
keyboardType = 'default',
onSubmitEditing,
disabled,
}) => {
const styling = styles(theme)
const { t } = useTranslation()
return (
<View style={styling.root}>
<TextInput
style={styling.input}
name={name}
onChangeText={form.handleChange(name)}
onBlur={form.handleBlur(name)}
value={value}
placeholder={placeholder}
placeholderTextColor={theme.colors.placeholder}
autoCapitalize="none"
multiline={multiline}
keyboardType={keyboardType}
onSubmitEditing={onSubmitEditing}
mode="outlined"
dense={true}
label={placeholder}
disabled={disabled}
/>
<ErrorMessage name={name} render={msg => <Text style={styling.error}>{msg}</Text>} />
</View>
)
}
Example #2
Source File: ReminderForm.js From jc-calendar with MIT License | 5 votes |
render() {
return (
<Formik
initialValues={this.getInitialValues()}
validationSchema={ReminderSchema}
onSubmit={this.handleSubmit}
>
<Form className="w-full flex flex-col gap-3">
<FormFieldset>
<FormLabel htmlFor="description">
What do you want to remember?
</FormLabel>
<div className="flex flex-row flex-wrap gap-2">
<Field
id="description"
name="description"
component={FormTextInput}
placeholder="e.g.: Buy milk"
className="flex-grow"
/>
<Field
name="color"
as={ReminderColorPicker}
className="flex-shrink"
/>
</div>
<ErrorMessage component={FormErrorMessage} name="description" />
<ErrorMessage component={FormErrorMessage} name="color" />
</FormFieldset>
<FormFieldset>
<FormLabel htmlFor="date">When?</FormLabel>
<div className="flex flex-row flex-wrap gap-2">
<Field
id="date"
name="date"
component={FormDatePicker}
className="flex-grow"
/>
<Field
id="time"
name="time"
component={FormTimePicker}
className="w-full sm:w-44"
/>
</div>
<ErrorMessage component={FormErrorMessage} name="date" />
<ErrorMessage component={FormErrorMessage} name="time" />
</FormFieldset>
<FormFieldset>
<FormLabel htmlFor="city">Where?</FormLabel>
<Field
id="city"
name="city"
component={FormTextInput}
placeholder="e.g.: New York City"
/>
<ErrorMessage component={FormErrorMessage} name="city" />
</FormFieldset>
<ReminderForecastContainer names={{ city: 'city', date: 'date' }} />
<FormActions>
<BaseButton
type="submit"
className="bg-indigo-700 hover:bg-indigo-500 text-white"
>
<CheckIcon svgClassName="w-6 h-6" />
Confirm
</BaseButton>
</FormActions>
</Form>
</Formik>
);
}
Example #3
Source File: index.js From realworld with MIT License | 5 votes |
export function LoginForm({ onSubmit }) {
return (
<div className="container page">
<div className="row">
<div className="col-md-6 offset-md-3 col-xs-12">
<h1 className="text-xs-center">Sign in</h1>
<p className="text-xs-center">
<Link href="/register">
<a>Need an account?</a>
</Link>
</p>
<Formik
validationSchema={validationSchema}
initialStatus={[]}
initialValues={{ input: { email: '', password: '' } }}
onSubmit={onSubmit}
>
<Form>
<ul className="error-messages">
<ErrorMessage component="li" name="input.email" />
<ErrorMessage component="li" name="input.password" />
<FormikStatusErrors />
</ul>
<fieldset className="form-group">
<label>Email</label>
<Field
name="input.email"
className="form-control form-control-lg"
type="text"
placeholder="[email protected]"
autoComplete="email"
/>
</fieldset>
<fieldset className="form-group">
<label>Password</label>
<Field
name="input.password"
className="form-control form-control-lg"
type="password"
placeholder="A strong password"
autoComplete="current-password"
/>
</fieldset>
<FormikSubmitButton className="btn btn-lg btn-primary pull-xs-right">
Sign in
</FormikSubmitButton>
</Form>
</Formik>
</div>
</div>
</div>
);
}
Example #4
Source File: index.js From realworld with MIT License | 5 votes |
export function RegisterForm({ onSubmit }) {
return (
<div className="container page">
<div className="row">
<div className="col-md-6 offset-md-3 col-xs-12">
<h1 className="text-xs-center">Sign up</h1>
<p className="text-xs-center">
<Link href="/login">
<a>Have an account?</a>
</Link>
</p>
<Formik
validationSchema={validationSchema}
initialStatus={[]}
initialValues={{
input: { email: '', username: '', password: '' },
}}
onSubmit={onSubmit}
>
<Form>
<ul className="error-messages">
<ErrorMessage component="li" name="input.username" />
<ErrorMessage component="li" name="input.email" />
<ErrorMessage component="li" name="input.password" />
<FormikStatusErrors />
</ul>
<fieldset className="form-group">
<label>Username</label>
<Field
className="form-control form-control-lg"
type="text"
name="input.username"
placeholder="john.doe"
autoComplete="username"
/>
</fieldset>
<fieldset className="form-group">
<label>Email</label>
<Field
className="form-control form-control-lg"
type="email"
name="input.email"
placeholder="[email protected]"
autoComplete="email"
/>
</fieldset>
<fieldset className="form-group">
<label>Password</label>
<Field
className="form-control form-control-lg"
type="password"
name="input.password"
placeholder="A secure password"
autoComplete="new-password"
/>
</fieldset>
<FormikSubmitButton className="btn btn-lg btn-primary pull-xs-right">
Sign up
</FormikSubmitButton>
</Form>
</Formik>
</div>
</div>
</div>
);
}
Example #5
Source File: index.js From realworld with MIT License | 5 votes |
export function UserCommentForm({
onSubmit,
username,
profile,
canCreateComment,
}) {
if (canCreateComment.value === false) return null;
return (
<Formik
enableReinitialize
validationSchema={validationSchema}
initialValues={{ body: '' }}
onSubmit={onSubmit}
>
<Form>
<ul className="error-messages">
<ErrorMessage component="li" name="body" />
<FormikStatusErrors />
</ul>
<div className="card comment-form">
<div className="card-block">
<Field
name="body"
as="textarea"
className="form-control"
placeholder="Write a comment..."
rows={3}
/>
</div>
<div className="card-footer">
<span style={{ display: 'inline-flex', verticalAlign: 'middle' }}>
<Image
alt={`Image of ${username}`}
className="comment-author-img"
height="32"
src={profile.imageUrl ?? '/images/smiley-cyrus.jpg'}
unoptimized={!!profile.imageUrl}
width="32"
/>
</span>
<Link href="/user/[username]" as={`/user/${username}`}>
<a className="comment-author">{username}</a>
</Link>
<FormikSubmitButton className="btn btn-sm btn-primary">
Post Comment
</FormikSubmitButton>
</div>
</div>
</Form>
</Formik>
);
}
Example #6
Source File: Login.jsx From react-signup-verification-boilerplate with MIT License | 5 votes |
function Login({ history, location }) {
const initialValues = {
email: '',
password: ''
};
const validationSchema = Yup.object().shape({
email: Yup.string()
.email('Email is invalid')
.required('Email is required'),
password: Yup.string().required('Password is required')
});
function onSubmit({ email, password }, { setSubmitting }) {
alertService.clear();
accountService.login(email, password)
.then(() => {
const { from } = location.state || { from: { pathname: "/" } };
history.push(from);
})
.catch(error => {
setSubmitting(false);
alertService.error(error);
});
}
return (
<Formik initialValues={initialValues} validationSchema={validationSchema} onSubmit={onSubmit}>
{({ errors, touched, isSubmitting }) => (
<Form>
<h3 className="card-header">Login</h3>
<div className="card-body">
<div className="form-group">
<label>Email</label>
<Field name="email" type="text" className={'form-control' + (errors.email && touched.email ? ' is-invalid' : '')} />
<ErrorMessage name="email" component="div" className="invalid-feedback" />
</div>
<div className="form-group">
<label>Password</label>
<Field name="password" type="password" className={'form-control' + (errors.password && touched.password ? ' is-invalid' : '')} />
<ErrorMessage name="password" component="div" className="invalid-feedback" />
</div>
<div className="form-row">
<div className="form-group col">
<button type="submit" disabled={isSubmitting} className="btn btn-primary">
{isSubmitting && <span className="spinner-border spinner-border-sm mr-1"></span>}
Login
</button>
<Link to="register" className="btn btn-link">Register</Link>
</div>
<div className="form-group col text-right">
<Link to="forgot-password" className="btn btn-link pr-0">Forgot Password?</Link>
</div>
</div>
</div>
</Form>
)}
</Formik>
)
}
Example #7
Source File: ForgotPassword.jsx From react-signup-verification-boilerplate with MIT License | 5 votes |
function ForgotPassword() {
const initialValues = {
email: ''
};
const validationSchema = Yup.object().shape({
email: Yup.string()
.email('Email is invalid')
.required('Email is required')
});
function onSubmit({ email }, { setSubmitting }) {
alertService.clear();
accountService.forgotPassword(email)
.then(() => alertService.success('Please check your email for password reset instructions'))
.catch(error => alertService.error(error))
.finally(() => setSubmitting(false));
}
return (
<Formik initialValues={initialValues} validationSchema={validationSchema} onSubmit={onSubmit}>
{({ errors, touched, isSubmitting }) => (
<Form>
<h3 className="card-header">Forgot Password</h3>
<div className="card-body">
<div className="form-group">
<label>Email</label>
<Field name="email" type="text" className={'form-control' + (errors.email && touched.email ? ' is-invalid' : '')} />
<ErrorMessage name="email" component="div" className="invalid-feedback" />
</div>
<div className="form-row">
<div className="form-group col">
<button type="submit" disabled={isSubmitting} className="btn btn-primary">
{isSubmitting && <span className="spinner-border spinner-border-sm mr-1"></span>}
Submit
</button>
<Link to="login" className="btn btn-link">Cancel</Link>
</div>
</div>
</div>
</Form>
)}
</Formik>
)
}
Example #8
Source File: TextField.js From real-frontend with GNU General Public License v3.0 | 5 votes |
TextField = ({
theme,
field: {
value,
name,
},
form,
placeholder,
multiline = false,
keyboardType = 'default',
onSubmitEditing,
disabled,
hideError,
autoCompleteType = 'off',
}) => {
const styling = styles(theme)
const { t } = useTranslation()
const onFocus = () => {
form.setFieldTouched(name, true)
}
const onBlur = (event) => {
form.handleBlur(name)(event)
// form.setFieldTouched(name, false)
}
const onChangeText = (event) => {
form.handleChange(name)(event)
}
return (
<View style={styling.root}>
<TextInput
style={styling.input}
name={name}
onChangeText={onChangeText}
onBlur={onBlur}
onFocus={onFocus}
value={value}
placeholder={placeholder}
placeholderTextColor={theme.colors.placeholder}
autoCapitalize="none"
multiline={multiline}
keyboardType={keyboardType}
onSubmitEditing={onSubmitEditing}
mode="outlined"
dense={true}
label={placeholder}
disabled={disabled}
autoCompleteType={autoCompleteType}
/>
{!hideError ?
<ErrorMessage name={name} render={msg => <Text style={styling.error}>{msg}</Text>} />
: null}
</View>
)
}
Example #9
Source File: Form.js From codeclannigeria-frontend with MIT License | 5 votes |
SignupForm = () => {
return (
<Formik
initialValues={{ firstName: '', lastName: '', email: '', password: '' }}
validationSchema={Yup.object({
firstName: Yup.string()
.max(15, 'Must be 15 characters or less')
.required('Required'),
lastName: Yup.string()
.max(20, 'Must be 20 characters or less')
.required('Required'),
email: Yup.string().email('Invalid email address').required('Required'),
password: Yup.string().required('Required'),
})}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
>
<SignupStyled>
<div id="wrapper">
<div id="signUpInfo">
<img
src="./img/codeclannglogo.png"
alt="Code Clan Logo"
id="logo"
/>
<h1 class="infoHeading">
welcome to CodeClan
<br />
Nigeria
</h1>
<p class="infoSubheading">sign up to</p>
<img src="./img/keyToComputer.png " alt="" id="infoIllustration" />
</div>
<div id="signUpDiv">
<h1 class="none show">register</h1>
<h2 class="none display">Create a Code Clan account</h2>
<Form id="signUpForm">
<AlertComponent variant="danger" />
<p className="info blue signUp">sign up with email</p>
<div className="nameInputGroup">
<label htmlFor="firstName">First Name</label>
<br />
<Field name="firstName" id="firstName" type="text" />
<ErrorMessage name="firstName" />
<label htmlFor="lastName">Last Name</label>
<Field name="lastName" type="text" />
<ErrorMessage name="lastName" />
</div>
<label htmlFor="email">Email Address</label>
<Field name="email" type="email" />
<ErrorMessage name="email" />
<p className="info blue privacy">
by clicking on this button, you agree to our Terms of use and
privacy policy
</p>
<button disabled className="submit">
Sign up
</button>
<p className="info blue signIn">
already have an account?
<span>
<Link to="/login/">Sign In</Link>
</span>
</p>
</Form>
</div>
</div>
</SignupStyled>
</Formik>
);
}
Example #10
Source File: FormField.jsx From react-chatengine-demo with MIT License | 5 votes |
FormField = ({ name, label, type = 'text' }) => (
<label>
{label}
<Field name={name} type={type} />
<ErrorMessage className="error" component="div" name={name} />
</label>
)
Example #11
Source File: form.js From proof-of-humanity-web with MIT License | 5 votes |
export function Field({ label, as = Input, sx, name, info, ...rest }) {
const validationSchema = useContext(ValidationSchemaContext);
const field = useField(name);
const [{ onChange }, { touched, error, initialValue }, { setValue }] = field;
const showError = touched && error;
return (
<Label onClick={(event) => event.preventDefault()}>
{typeof label === "function" ? label({ field }) : label}
<Box
sx={{
marginTop: 1,
position: "relative",
...(as === Checkbox && { display: "flex" }),
}}
>
<_Field
className={showError ? "error" : undefined}
as={as}
sx={{
":focus": {
boxShadow(theme) {
return `0 0 6px ${alpha("highlight", 0.25)(theme)}`;
},
},
...(typeof sx === "function" ? sx({ field }) : sx),
}}
name={name}
onChange={(event) => {
try {
event.target.value = reach(validationSchema, name).render(
event.target.value
);
onChange(event);
} catch {
onChange(event);
}
}}
{...rest}
/>
{as === Checkbox && info && (
<Text variant="forms.field.info" sx={{ marginLeft: 2 }}>
{info}
</Text>
)}
{as === Input && showError && (
<X
variant="forms.field.error.icon"
sx={{
position: "absolute",
right: 2,
top: "50%",
transform: "translateY(-50%)",
}}
onClick={(event) => {
event.preventDefault();
setValue(initialValue);
}}
/>
)}
</Box>
{as !== Checkbox && info && (
<Text variant="forms.field.info">{info}</Text>
)}
<Text variant="forms.field.error">
<ErrorMessage name={name} />
</Text>
</Label>
);
}
Example #12
Source File: Feedback.js From Simplify-Testing-with-React-Testing-Library with MIT License | 5 votes |
Feedback = props => (
<main className="flex flex-col w-2/3 m-auto py-2">
<h1 className="text-2xl text-gray-900 font-semibold m-auto">
We'd love to hear your thoughts!
</h1>
<Formik
initialValues={{ name: '', email: '', rating: '', comments: '' }}
validate={formValidator}
onSubmit={values => props.onSubmit(values)}
>
{({ isSubmitting }) => (
<Form className="form bg-white p-6 my-10 relative">
<p className="text-red-600 mb-1">
All fields marked with * are required
</p>
<label>
Name *
<Field
type="text"
name="name"
placeholder="Name here"
className="border p-2 w-full mt-3"
/>
</label>
<ErrorMessage name="name" component="div" className="text-red-600" />
<label>
Email *
<Field
type="email"
name="email"
placeholder="Email here"
className="border p-2 w-full mt-3"
/>
</label>
<ErrorMessage name="email" component="div" className="text-red-600" />
<label>
Rating *
<Field as="select" name="rating" className="border p-2 w-full mt-3">
<option value=""></option>
<option value="Awesome">Awesome</option>
<option value="Good">Good</option>
<option value="Bad">Bad</option>
</Field>
</label>
<ErrorMessage
name="rating"
component="div"
className="text-red-600"
/>
<label>
Comments *
<Field
as="textarea"
name="comments"
placeholder="comments here"
className="border p-2 w-full mt-3"
/>
</label>
<ErrorMessage
name="comments"
component="div"
className="text-red-600"
/>
<button
type="submit"
disabled={isSubmitting}
className="w-full mt-6 bg-blue-600 hover:bg-blue-500 text-white font-semibold p-3"
>
Submit
</button>
</Form>
)}
</Formik>
</main>
)
Example #13
Source File: FormLayout.js From umami with MIT License | 5 votes |
FormError = ({ name }) => {
return <ErrorMessage name={name}>{msg => <ErrorTag msg={msg} />}</ErrorMessage>;
}
Example #14
Source File: index.jsx From elliot-serverless-ecommerce with MIT License | 4 votes |
CreditCardForm = ({ stripe, checkout }) => {
const { locale, formatMessage } = useIntl();
const router = useRouter();
const {
state: { data: cart }
} = useCart();
const {
state: currency,
exchangeRate,
loading: loadingCurrency
} = useCurrency();
const { setOrderStatus } = useDispatchCheckout();
const [loadingShippingInfo, setLoadingShippingInfo] = useState(false);
const [paymentLoading, setPaymentLoading] = useState(false);
const [cardError, setCardError] = useState(false);
const [paymentState, setPaymentState] = useState(null);
const [validCard, setCardValidity] = useState(false);
const [cardOnBlurMessage, setCardOnBlurMessage] = useState("");
const [shippingOptions, setShippingOptions] = useState([]);
const [
selectedShippingOptionIndex,
setSelectedShippingOptionIndex
] = useState(0);
const [
lastAddressUsedToFetchShipping,
setLastAddressUsedToFetchShipping
] = useState({
city: "",
state: "",
country: "",
zipCode: ""
});
const [touchedErrors, setTouchedErrors] = useState({});
const [optionalShippingAddress, setOptionalShippingAddress] = useState(false);
const hasAddressErrors = errors => {
return (
Object.keys(errors).filter(
key =>
["addressLine1", "city", "state", "country", "zipCode"].indexOf(
key
) !== -1
).length > 0
);
};
const isAddressDirty = (fieldName, value) => {
return (
["city", "country", "state", "zipCode"].indexOf(fieldName) !== -1 &&
value !== lastAddressUsedToFetchShipping[fieldName]
);
};
const shippingOption = useMemo(
() => getDisplayedShippingOptions({ shippingOptions, checkout }),
[JSON.stringify(shippingOptions)]
);
const {
shippingOptions: displayedShippingOptions,
freeShipping
} = shippingOption;
const { shippingTotal } = useShippingInfo();
const { promotion } = useCheckout();
const { orderTotal } = useOrderSummary({
shippingTotal,
exchangeRate,
cart,
promotion
});
useShippingStateUpdater({
selectedShippingOptionIndex,
shippingOption
});
const handleAddressSelected = async (
addressLine1,
addressLine2,
city,
selectedState,
selectedCountry,
zipCode
) => {
setLoadingShippingInfo(true);
const shippingDestination = {
line1: addressLine1,
line2: addressLine2,
city,
state: selectedState,
country: selectedCountry,
zip: zipCode
};
const shippingOptions = await getShippingOptions({
shippingDestination,
cart,
checkout
});
setShippingOptions(shippingOptions);
setLoadingShippingInfo(false);
setLastAddressUsedToFetchShipping({
city,
state: selectedState,
country: selectedCountry,
zipCode: zipCode
});
};
const onFieldBlur = async (fieldName, values, dirty, errors) => {
const updatedTouchedErrors = { ...touchedErrors };
if (fieldName in errors) {
updatedTouchedErrors[fieldName] = true;
} else if (fieldName in touchedErrors) {
delete updatedTouchedErrors[fieldName];
}
const shippingDestination = {
line1: values.addressLine1,
line2: values.addressLine2,
city: values.city,
state: values.state,
country: values.country,
zip: values.zipCode
};
setTouchedErrors(updatedTouchedErrors);
if (dirty && !hasAddressErrors(errors)) {
if (
!displayedShippingOptions ||
isAddressDirty(fieldName, values[fieldName])
) {
const shippingOptions = await getShippingOptions({
shippingDestination,
cart,
checkout
});
setShippingOptions(shippingOptions);
}
const updatedLastAddressUsedToFetchShipping = {
...lastAddressUsedToFetchShipping
};
updatedLastAddressUsedToFetchShipping[fieldName] = values[fieldName];
setLastAddressUsedToFetchShipping(updatedLastAddressUsedToFetchShipping);
}
};
const checkValidCard = ({ error, complete }) => {
if (cardOnBlurMessage) {
setCardOnBlurMessage("");
}
setCardError(error && error.message);
if (!complete) {
setCardOnBlurMessage(formatMessage({ id: "validation.cc.fields" }));
} else {
setCardValidity(true);
}
};
const locationSearchInputComponent = ({
field,
form,
onBlur,
value,
fieldsToUpdate,
optional
}) => {
return (
<LocationSearchInput
field={field}
form={form}
fieldsToUpdate={fieldsToUpdate}
placeholder="33 Irving Place"
onBlur={onBlur}
onSelect={handleAddressSelected}
value={value}
optional={optional}
/>
);
};
return (
<Formik
initialValues={{
name: "",
email: "",
phone: "",
addressLine1: "",
addressLine2: "",
city: "",
state: "",
country: "",
zipCode: "",
addressLine1_optional: "",
addressLine2_optional: "",
city_optional: "",
state_optional: "",
country_optional: "",
zipCode_optional: ""
}}
validationSchema={Yup.object().shape({
name: Yup.string()
.max(100, formatMessage({ id: "validation.full_name" }))
.required(formatMessage({ id: "validation.required" })),
email: Yup.string()
.email(formatMessage({ id: "validation.invalid_email" }))
.required(formatMessage({ id: "validation.required" })),
phone: Yup.string(),
addressLine1: Yup.string().required(
formatMessage({ id: "validation.required" })
),
addressLine2: Yup.string(),
city: Yup.string().required(
formatMessage({ id: "validation.required" })
),
state: Yup.string().required(),
country: Yup.string().required(
formatMessage({ id: "validation.required" })
),
zipCode: Yup.string().required(
formatMessage({ id: "validation.required" })
),
addressLine1_optional: !optionalShippingAddress
? Yup.string()
: Yup.string().required(formatMessage({ id: "validation.required" })),
addressLine2_optional: !optionalShippingAddress
? Yup.string()
: Yup.string(),
city_optional: !optionalShippingAddress
? Yup.string()
: Yup.string().required(formatMessage({ id: "validation.required" })),
state_optional: !optionalShippingAddress
? Yup.string()
: Yup.string().required(),
country_optional: !optionalShippingAddress
? Yup.string()
: Yup.string().required(formatMessage({ id: "validation.required" })),
zipCode_optional: !optionalShippingAddress
? Yup.string()
: Yup.string().required(formatMessage({ id: "validation.required" }))
})}
onSubmit={async values => {
try {
// Within the context of `Elements`, this call to createToken knows which Element to
// tokenize, since there's only one in this group.
const { token } = await stripe.createToken({ name: values.name });
setPaymentLoading(true);
if (!token) {
console.error("NO TOKEN");
return;
}
const {
name,
addressLine1: line1,
addressLine2: line2,
city,
state,
country,
zipCode: postalCode,
phone,
email,
shipToAddress,
shipToCity,
shipToCountry,
shipToState,
shipToZipCode,
addressLine1_optional,
addressLine2_optional,
city_optional,
state_optional,
country_optional,
zipCode_optional
} = values;
const data = {
email,
line1: optionalShippingAddress ? addressLine1_optional : line1,
line2: optionalShippingAddress ? addressLine2_optional : line2,
city: optionalShippingAddress ? city_optional : city,
state: optionalShippingAddress ? state_optional : state,
country: optionalShippingAddress ? country_optional : country,
postalCode: optionalShippingAddress ? zipCode_optional : postalCode,
phone,
name: name.slice(0, 100),
shipToAddress,
shipToCity,
shipToCountry,
shipToState,
shipToZipCode
};
const payload = getShippingPayload({
checkout,
cart,
data,
token,
shippingOptions: adjustShippingOptionsForChoices({
displayedShippingOptions,
shippingOptions,
checkout,
selectedShippingOptionIndex
}),
selectedShippingOptionIndex
});
const res = await fetch(
"https://us-east1-elliot-192017.cloudfunctions.net/createOrderShipping",
{
method: "post",
body: JSON.stringify(payload),
headers: { "Content-Type": "application/json" }
}
);
if (res.ok) {
setPaymentState("PAYMENT SUCCESSFUL");
setOrderStatus("PAYMENT SUCCESSFUL");
router.push(`/${locale}/successful-order`);
} else {
setPaymentState("PAYMENT FAILED");
setOrderStatus("PAYMENT FAILED");
router.push(`/${locale}/order-failed`);
}
} catch (error) {
setPaymentState("PAYMENT FAILED");
setOrderStatus("PAYMENT FAILED");
router.push(`/${locale}/order-failed`);
} finally {
setPaymentLoading(false);
}
}}
render={({ dirty, errors, setFieldValue, values, setFieldTouched }) => {
const canSubmit =
dirty &&
isEmpty(errors) &&
validCard &&
!cardError &&
displayedShippingOptions &&
!paymentLoading;
return (
<Form>
<>
{[
"name",
"email",
"phone",
"addressLine1",
"addressLine2",
"city",
"state",
"country",
"zipCode",
"addressLine1_optional",
"addressLine2_optional",
"city_optional",
"state_optional",
"country_optional",
"zipCode_optional"
].map(field => (
<FastField
key={field}
name={field}
autoComplete="on"
style={{ display: "none" }}
/>
))}
</>
<Wrapper>
<PaymentButtons />
<h4>
<FormattedMessage id="checkout.enter_payment_details" />
</h4>
<Flex align="flex-start">
<Item col={6} colTablet={12} colMobile={12} gap={2}>
<FieldWrapper>
<label>
<FormattedMessage id="checkout.form.email" />
</label>
<Field
name="email"
type="email"
autoComplete="new-password"
as={InputField}
placeholder="[email protected]"
/>
<ErrorMessage component={ErrorField} name="email" />
</FieldWrapper>
</Item>
<Item col={6} colTablet={12} colMobile={12} gap={2}>
<FieldWrapper>
<label>
<FormattedMessage id="checkout.form.phone" />
</label>
<Field
country="us"
name="phone"
autoComplete="new-password"
value={values.phone}
component={PhoneInput}
placeholder={3477150728}
onBlur={() => setFieldTouched("phone")}
onChange={value => setFieldValue("phone", value)}
buttonStyle={{
background: "#fafafa",
border: "2px solid #eaeaea",
borderRadius: 0
}}
dropdownStyle={{ background: "#fff" }}
inputStyle={{
width: "100%",
lineHeight: 49,
fontSize: "12px",
color: "#222",
height: 50,
border: "2px solid #eaeaea",
borderRadius: "0"
}}
/>
<ErrorMessage component={ErrorField} name="phone" />
</FieldWrapper>
</Item>
</Flex>
<FieldWrapper>
<label>
<FormattedMessage id="checkout.form.full_name" />
</label>
<Field
name="name"
as={InputField}
autoComplete="new-password"
placeholder="Dublin Skywalker"
/>
<ErrorMessage component={ErrorField} name="name" />
</FieldWrapper>
<ShippingAddress
locationComponent={locationSearchInputComponent}
fieldsToUpdate={[
"addressLine1",
"city",
"state",
"country",
"zipCode"
]}
onFieldBlur={onFieldBlur}
values={values}
dirty={dirty}
errors={errors}
/>
<CheckboxWrapper>
<CheckBox>
<input
type="checkbox"
onChange={() =>
setOptionalShippingAddress(!optionalShippingAddress)
}
/>
<span>
<FormattedMessage id="checkout.ship_to_different_address" />
</span>
</CheckBox>
</CheckboxWrapper>
{optionalShippingAddress && (
<ShippingAddress
locationComponent={locationSearchInputComponent}
fieldsToUpdate={[
"addressLine1_optional",
"city_optional",
"state_optional",
"country_optional",
"zipCode_optional"
]}
onFieldBlur={onFieldBlur}
values={values}
dirty={dirty}
errors={errors}
optional
/>
)}
<FieldWrapper>
<label style={{ marginRight: "1rem" }}>
<FormattedMessage id="checkout.shipping_method" />
</label>
{loadingShippingInfo && <Loader />}
{freeShipping ? (
<RadioButton>
<input
type="radio"
id="shipping-free"
value="free"
name="shipping"
checked
/>
<label htmlFor="shipping-free">
<FormattedMessage id="shipping.free" />
</label>
</RadioButton>
) : displayedShippingOptions ? (
displayedShippingOptions.map(
({ provider, type, days }, i) => {
let label = `${provider} ${type}`;
if (days) {
label += ` - Arrives in ${days} day(s)`;
}
return (
<RadioButton key={i}>
<input
type="radio"
id={`shipping-${i}`}
value={selectedShippingOptionIndex}
name="shipping"
onChange={e =>
setSelectedShippingOptionIndex(e.target.value)
}
/>
<label htmlFor={`shipping-${i}`}>{label}</label>
</RadioButton>
);
}
)
) : (
!loadingShippingInfo && (
<div>
<strong>
<FormattedMessage id="checkout.form.complete_shipping_info" />
</strong>
</div>
)
)}
</FieldWrapper>
<FieldWrapper>
<label>
<FormattedMessage id="checkout.form.credit_card" />
{cardError && (
<span>
-
<span
style={{
color: "#e10007",
fontSize: "small"
}}
>
{cardError}
</span>
</span>
)}
</label>
<CreditCardWrap>
<div>
<CardElement
style={{
base: {
"::placeholder": {
color: "#cfcfcf"
},
fontSize: "16px"
}
}}
onChange={checkValidCard}
onBlur={() => {
if (!cardError && cardOnBlurMessage) {
setCardError(cardOnBlurMessage);
}
}}
/>
</div>
</CreditCardWrap>
</FieldWrapper>
<div>
<BuyButton
canSubmit={canSubmit}
price={orderTotal}
currency={currency}
paymentState={paymentState}
loadingCurrency={loadingCurrency}
paymentLoading={paymentLoading}
/>
<Link href="/[lang]/" as={`/${locale}/`}>
<Button as="a" wide variant="secondary">
<FormattedMessage id="button.go_back" />
</Button>
</Link>
</div>
</Wrapper>
</Form>
);
}}
/>
);
}
Example #15
Source File: index.jsx From elliot-serverless-ecommerce with MIT License | 4 votes |
TabReview = () => (
<Review>
<h4>1 review for Contrasting Design T-Shirt</h4>
<Flex align="center">
<Item className="user_image" col={1} colTablet={12} colMobile={12}>
<img src="https://i.pravatar.cc/70?img=44" alt="" />
</Item>
<Item
className="user__information"
col={11}
colTablet={12}
colMobile={12}
>
<Stars stars={4} />
<h4>
Martin Katrina <span>- June 20, 2019</span>
</h4>
<p>Aenean sit amet odio est.</p>
</Item>
</Flex>
<h5>Add a review</h5>
<p>
<small>Connect with:</small>
</p>
<ul className="social__connect">
<li className="social__connect__item">
<a href="#">
<FacebookIconLogin />
</a>
</li>
<li className="social__connect__item">
<a href="#">
<TwiterIconLogin />
</a>
</li>
</ul>
<p>
<small>
Your email address will not be published. Required fields are marked *
</small>
</p>
<Formik
initialValues={{ email: "", name: "", review: "" }}
validationSchema={Yup.object().shape({
name: Yup.string().required("This field is required"),
email: Yup.string()
.email("Invalid email")
.required("This field is required"),
review: Yup.string().required("This field is required")
})}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
setSubmitting(false);
}, 400);
}}
>
{({ isSubmitting, errors, touched }) => (
<Form>
<InputContainer>
<Stars stars={4} />
</InputContainer>
<InputContainer
className={errors.review && touched.review && "has__error"}
>
<label htmlFor="review">Review:</label>
<Field type="text" name="review" component="textarea" rows="6" />
<ErrorMessage name="review" component="span" />
</InputContainer>
<Flex align="start">
<Item col={6} colTablet={12} colMobile={12}>
<InputContainer
className={errors.email && touched.email && "has__error"}
>
<label htmlFor="name">Email:</label>
<Field type="email" name="email" />
<ErrorMessage name="email" component="span" />
</InputContainer>
</Item>
<Item col={6} colTablet={12} colMobile={12}>
<InputContainer
className={errors.name && touched.name && "has__error"}
>
<label htmlFor="name">Name:</label>
<Field type="text" name="name" />
<ErrorMessage name="name" component="span" />
</InputContainer>
</Item>
</Flex>
<Button variant="primary" type="submit" disabled={isSubmitting}>
Submit
</Button>
</Form>
)}
</Formik>
</Review>
)
Example #16
Source File: Signup.js From react-chat-app with MIT License | 4 votes |
Signup = () => {
const history = useHistory();
const [serverError, setServerError] = useState("");
const [loading, setLoading] = useState(false);
function lowerLetters(str) {
return str.toLowerCase();
}
const signup = ({ userName, password }, { setSubmitting }) => {
alert("The limit for new accounts has been reached. Please use Sample Account")
return null
setLoading(true)
//@chat.engine is added to login because of Firebase requiring email string
fb.auth
.createUserWithEmailAndPassword(
`${encodeURIComponent(lowerLetters(userName))}@chat.engine`,
password
)
.then((res) => {
console.log("Firebase account created");
})
.catch((err) => {
if (err.code === "auth/email-already-in-use") {
setServerError("An account with this username already exists");
} else {
setServerError(
"We're having trouble signing you up. Please try again."
);
}
})
.finally(() => {
setSubmitting(false)
setLoading(false)
});
};
return (
<div className="auth-form signup-fields">
<div className="logo">
<CommentOutlined />
<div className="logo-text">
<div className="logo-text-first"> Chat</div>
<div className="logo-text-second"> App</div>
</div>
</div>
<Formik
onSubmit={signup}
validateOnMount={true}
initialValues={defaultValues}
validationSchema={validationSchema}
>
{({ isValid, isSubmitting }) => (
<Form>
<div className="login-fields ">
<div className="login-field">
<UserOutlined />
<FormField name="userName" placeholder="Username" />
</div>
<ErrorMessage component='div' name="userName" className="error" />
<div className="login-field">
<LockOutlined />
<FormField name="password" type="password" placeholder="Password" />
</div>
<ErrorMessage component='div' name="password" className="error" />
<div className="login-field">
<LockOutlined />
<FormField name="verifyPassword" placeholder="Verify Password" type="password" />
</div>
<ErrorMessage component='div' name="verifyPassword" className="error" />
</div>
{!loading ?
<button type="submit">
Sign Up (Disabled)
</button> : <div className="loading-image"><img src={loadingAnimation} alt="" /></div>}
<div className="auth-link-container already-account">
Already have an account?{" "}
<span className="auth-link signup-text" onClick={() => history.push("react-chat-app")}>
Log In!
</span>
</div>
</Form>
)}
</Formik>
{!!serverError && <div className="error">{serverError}</div>}
</div>
);
}
Example #17
Source File: Login.js From react-chat-app with MIT License | 4 votes |
Login = () => {
const [serverError, setServerError] = useState("");
const history = useHistory();
const [loading, setLoading] = useState(false);
function lowerLetters(str) {
return str.toLowerCase();
}
const login = ({ userName, password }, { setSubmitting }) => {
setLoading(true)
// @chat.engine is added to login because of Firebase requiring email string
fb.auth
.signInWithEmailAndPassword(
`${encodeURIComponent(lowerLetters(userName))}@chat.engine`,
password
)
.then((res) => {
if (!res.user) {
setServerError(
"We're having trouble logging you in. Please try again."
);
}
})
.catch((err) => {
console.log(err);
if (err.code === "auth/wrong-password") {
setServerError("Username or password is invalid");
} else if (err.code === "auth/user-not-found") {
setServerError("No account for this username");
} else {
setServerError("Something went wrong :(");
}
})
.finally(() => {
setLoading(false)
});
};
return (
<div className="auth-form">
<div className="logo">
<CommentOutlined />
<div className="logo-text">
<div className="logo-text-first"> Chat</div>
<div className="logo-text-second"> App</div>
</div>
</div>
<Formik
onSubmit={login}
validateOnMount={true}
initialValues={defaultValues}
validationSchema={validationSchema}
>
{({ isValid, isSubmitting }) => (
<Form>
<div className="login-fields">
<div className="login-field">
<UserOutlined />
<FormField name="userName" placeholder="Username" /></div>
<ErrorMessage component='div' name="userName" className="error" /> <br />
<div className="login-field">
<LockOutlined />
<FormField name="password" placeholder="Password" type="password" />
</div>
<ErrorMessage component='div' name="password" className="error" />
</div>
<div className="auth-link-container">
Don't have an account?{" "}
<span
className="auth-link signup-text"
onClick={() => history.push("signup")}
>
Sign Up!
</span>
</div>
{!loading ?
<div className="login-buttons">
<button type="submit">
Login
</button>
<button
className="sample-account-button"
onClick={() => {
login({userName: "john doe", password: "password123"}, { setSubmitting: true })
}}>
Sample Account
</button>
</div> : <div className="loading-image"><img src={loadingAnimation} alt="" /></div>}
{!!serverError && <div className="error server-error">{serverError}</div>}
</Form>
)}
</Formik>
<div className="social-media">
<div className="social-media-header">
<hr /> Login with social media<hr />
</div>
<div className="social-login">
<div
className="google"
/*onClick={() => fb.auth.signInWithRedirect(googleProvider)}*/
onClick={() => {
alert("The limit for new accounts has been reached. Please use Sample Account")
}}
>
<GoogleOutlined /> Google
</div>
<div
className="google"
/*onClick={() => fb.auth.signInWithRedirect(facebookProvider)}*/
onClick={() => {
alert("The limit for new accounts has been reached. Please use Sample Account")
}}
>
<FacebookOutlined /> Facebook
</div>
</div>
</div>
</div>
);
}
Example #18
Source File: index.js From realworld with MIT License | 4 votes |
export function UserSettingsForm({ onSubmit, username, email, profile }) {
const { bio = '', imageUrl } = profile;
return (
<div className="container page">
<div className="row">
<div className="col-md-6 offset-md-3 col-xs-12">
<h1 className="text-xs-center">Your Settings</h1>
<Formik
validationSchema={validationSchema}
initialStatus={[]}
enableReinitialize
initialValues={{
username,
input: {
email,
password: '',
username,
profile: {
bio,
imageUrl: imageUrl ?? '',
},
},
}}
onSubmit={onSubmit}
>
<Form>
<ul className="error-messages">
<ErrorMessage component="li" name="username" />
<ErrorMessage component="li" name="input.email" />
<ErrorMessage component="li" name="input.password" />
<ErrorMessage component="li" name="input.username" />
<ErrorMessage component="li" name="input.profile.bio" />
<ErrorMessage component="li" name="input.profile.imageUrl" />
<FormikStatusErrors />
</ul>
<fieldset>
<fieldset className="form-group">
<label>Email</label>
<Field
name="input.email"
className="form-control form-control-lg"
type="email"
placeholder="[email protected]"
autoComplete="email"
/>
</fieldset>
<fieldset className="form-group">
<label>Password</label>
<Field
name="input.password"
className="form-control form-control-lg"
type="password"
placeholder="A secure password"
autoComplete="new-password"
/>
</fieldset>
<fieldset className="form-group">
<label>Username</label>
<Field
name="input.username"
className="form-control form-control-lg"
type="text"
placeholder="john.doe"
autoComplete="username"
/>
</fieldset>
<fieldset className="form-group">
<label>Bio</label>
<Field
name="input.profile.bio"
as="textarea"
className="form-control form-control-lg"
rows={8}
placeholder="John Doe is a Loan Officer at XYZ Bank, where John processes loan applications from start to finish, including mortgage refinancing and educating clients about their different financing options. John has worked with reputable real estate agencies, including ReMax, Century 21, and Coldwell Banker, among others. John helps homeowners and new buyers secure a loan that suits their budget and goals. You can expect 100% transparency, no horror stories, and nasty surprises when working with John. John is a cat-lover and CMAS diver from Michigan."
/>
</fieldset>
<fieldset className="form-group">
<label>Image Url</label>
<Field
name="input.profile.imageUrl"
className="form-control"
type="text"
placeholder="http://example.com/your-photo.jpg"
/>
</fieldset>
<FormikSubmitButton className="btn btn-lg btn-primary pull-xs-right">
Update Settings
</FormikSubmitButton>
</fieldset>
</Form>
</Formik>
</div>
</div>
</div>
);
}
Example #19
Source File: ReviewFormPage.jsx From breviews with MIT License | 4 votes |
ReviewForm = (props) => {
const { onSubmit, handleStar, ratingVal, validate } = props;
return (
<div>
<Formik
validateOnChange={true}
initialValues={{
customerName: "",
review: "",
pros: "",
cons: "",
title: "",
email: "",
acceptTerms: false,
ratingVal: ratingVal,
linkedin: ""
}}
validate={validate}
onSubmit={onSubmit}
>
{({ values, errors, isSubmitting }) => (
<Form className="review-submit-form">
<div>
<label htmlFor="customerName">Name* </label>
<Field
placeholder="Name"
name="customerName"
type="input"
/>
<ErrorMessage name="customerName" render={msg => <div className="form-errors">{msg}</div>} />
</div>
<div>
<label>Select Rating*</label>
<MyStarInput name="ratingVal" handleStar={handleStar} ratingVal={ratingVal} value={ratingVal}/>
<ErrorMessage name="ratingVal" render={msg => <div className="form-errors">{msg}</div>} />
</div>
<div>
<label htmlFor="title"> Title of your review* </label>
<Field
placeholder="Best bootcamp, reccomend..."
name="title"
type="input"
/>
<span className="input-footers">( 3 word minimum )</span>
<ErrorMessage name="title" render={msg => <div className="form-errors">{msg}</div>} />
</div>
<div>
<label htmlFor="review"> Your Review* </label>
<Field
className="review"
name="review"
type="textarea"
component="textarea"
rows={5}
cols={20}
/>
<span className="input-footers">( 15 word minimum )</span>
<ErrorMessage name="review" render={msg => <div className="form-errors">{msg}</div>} />
</div>
<div>
<label htmlFor="pros"> Pros </label>
<Field
className="pros"
placeholder="Share some pros of this bootcamp"
name="pros"
type="textarea"
component="textarea"
/>
</div>
<div>
<label htmlFor="cons"> Cons </label>
<Field
className="cons"
placeholder="Share some cons of this bootcamp"
name="cons"
type="textarea"
component="textarea"
/>
</div>
<div>
<label htmlFor="email"> Email* </label>
<Field
name="email"
type="email"
/>
<ErrorMessage name="email" render={msg => <div className="form-errors">{msg}</div>} />
</div>
<div>
<label htmlFor="linkedin"> LinkedIn Url* </label>
<Field
name="linkedin"
type="input"
/>
<ErrorMessage name="linkedin" render={msg => <div className="form-errors">{msg}</div>} />
</div>
<div className="checkboxes">
<Field name="acceptTerms" type="checkbox" className="checkbox"/>
<label className="checkbox-label">I agree to BootcampAvenue Terms of Use. This review of my experience at this bootcamp is truthful*</label>
<ErrorMessage name="acceptTerms" render={msg => <div className="form-errors">{msg}</div>} />
</div>
<div>
<button disabled={isSubmitting} type="submit" className="form-submit-btn">
Post Review
</button>
{/* for testing purposes only */}
{/* <pre>{JSON.stringify(values, null, 2)}</pre>
<pre>{JSON.stringify(errors, null, 2)}</pre> */}
</div>
</Form>
)}
</Formik>
</div>
);
}
Example #20
Source File: index.js From realworld with MIT License | 4 votes |
export function ArticleForm({
slug,
title,
description,
body,
tags,
onSubmit,
}) {
const initialValues = {
slug,
input: {
title,
description,
body,
tagIds: tags.map(tag => tag.id),
},
};
return (
<div className="container page">
<div className="row">
<div className="col-md-10 offset-md-1 col-xs-12">
<Formik
validationSchema={
slug ? updateValidationSchema : createValidationSchema
}
initialValues={initialValues}
onSubmit={onSubmit}
>
<Form id="article-form">
<ul className="error-messages">
<ErrorMessage component="li" name="slug" />
<ErrorMessage component="li" name="input.title" />
<ErrorMessage component="li" name="input.description" />
<ErrorMessage component="li" name="input.body" />
<ErrorMessage component="li" name="input.tagIds" />
<FormikStatusErrors />
</ul>
<fieldset>
<fieldset className="form-group">
<label htmlFor="article-form-title-input">Title</label>
<Field
name="input.title"
type="text"
id="article-form-title-input"
className="form-control form-control-lg"
placeholder="How to build webapps that scale"
/>
</fieldset>
<fieldset className="form-group">
<label htmlFor="article-form-description-input">
Description
</label>
<Field
name="input.description"
type="text"
id="article-form-description-input"
className="form-control"
placeholder="Web development technologies have evolved at an incredible clip over the past few years."
/>
</fieldset>
<fieldset className="form-group">
<label htmlFor="article-form-body-textarea">Body</label>
<Field
name="input.body"
as="textarea"
className="form-control"
id="article-form-body-textarea"
rows={8}
placeholder={`# Introducing RealWorld.\n\nIt's a great solution for learning how other frameworks work.`}
/>
</fieldset>
<fieldset className="form-group">
<label htmlFor="article-form-tags-ids-input">Tags</label>
<TagsInput
name="input.tagIds"
id="article-form-tags-ids-input"
/>
</fieldset>
<FormikSubmitButton className="btn btn-lg pull-xs-right btn-primary">
Publish Article
</FormikSubmitButton>
</fieldset>
</Form>
</Formik>
</div>
</div>
</div>
);
}
Example #21
Source File: AddEdit.jsx From react-signup-verification-boilerplate with MIT License | 4 votes |
function AddEdit({ history, match }) {
const { id } = match.params;
const isAddMode = !id;
const initialValues = {
title: '',
firstName: '',
lastName: '',
email: '',
role: '',
password: '',
confirmPassword: ''
};
const validationSchema = Yup.object().shape({
title: Yup.string()
.required('Title is required'),
firstName: Yup.string()
.required('First Name is required'),
lastName: Yup.string()
.required('Last Name is required'),
email: Yup.string()
.email('Email is invalid')
.required('Email is required'),
role: Yup.string()
.required('Role is required'),
password: Yup.string()
.concat(isAddMode ? Yup.string().required('Password is required') : null)
.min(6, 'Password must be at least 6 characters'),
confirmPassword: Yup.string()
.when('password', (password, schema) => {
if (password) return schema.required('Confirm Password is required');
})
.oneOf([Yup.ref('password')], 'Passwords must match')
});
function onSubmit(fields, { setStatus, setSubmitting }) {
setStatus();
if (isAddMode) {
createUser(fields, setSubmitting);
} else {
updateUser(id, fields, setSubmitting);
}
}
function createUser(fields, setSubmitting) {
accountService.create(fields)
.then(() => {
alertService.success('User added successfully', { keepAfterRouteChange: true });
history.push('.');
})
.catch(error => {
setSubmitting(false);
alertService.error(error);
});
}
function updateUser(id, fields, setSubmitting) {
accountService.update(id, fields)
.then(() => {
alertService.success('Update successful', { keepAfterRouteChange: true });
history.push('..');
})
.catch(error => {
setSubmitting(false);
alertService.error(error);
});
}
return (
<Formik initialValues={initialValues} validationSchema={validationSchema} onSubmit={onSubmit}>
{({ errors, touched, isSubmitting, setFieldValue }) => {
useEffect(() => {
if (!isAddMode) {
// get user and set form fields
accountService.getById(id).then(user => {
const fields = ['title', 'firstName', 'lastName', 'email', 'role'];
fields.forEach(field => setFieldValue(field, user[field], false));
});
}
}, []);
return (
<Form>
<h1>{isAddMode ? 'Add User' : 'Edit User'}</h1>
<div className="form-row">
<div className="form-group col">
<label>Title</label>
<Field name="title" as="select" className={'form-control' + (errors.title && touched.title ? ' is-invalid' : '')}>
<option value=""></option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss">Miss</option>
<option value="Ms">Ms</option>
</Field>
<ErrorMessage name="title" component="div" className="invalid-feedback" />
</div>
<div className="form-group col-5">
<label>First Name</label>
<Field name="firstName" type="text" className={'form-control' + (errors.firstName && touched.firstName ? ' is-invalid' : '')} />
<ErrorMessage name="firstName" component="div" className="invalid-feedback" />
</div>
<div className="form-group col-5">
<label>Last Name</label>
<Field name="lastName" type="text" className={'form-control' + (errors.lastName && touched.lastName ? ' is-invalid' : '')} />
<ErrorMessage name="lastName" component="div" className="invalid-feedback" />
</div>
</div>
<div className="form-row">
<div className="form-group col-7">
<label>Email</label>
<Field name="email" type="text" className={'form-control' + (errors.email && touched.email ? ' is-invalid' : '')} />
<ErrorMessage name="email" component="div" className="invalid-feedback" />
</div>
<div className="form-group col">
<label>Role</label>
<Field name="role" as="select" className={'form-control' + (errors.role && touched.role ? ' is-invalid' : '')}>
<option value=""></option>
<option value="User">User</option>
<option value="Admin">Admin</option>
</Field>
<ErrorMessage name="role" component="div" className="invalid-feedback" />
</div>
</div>
{!isAddMode &&
<div>
<h3 className="pt-3">Change Password</h3>
<p>Leave blank to keep the same password</p>
</div>
}
<div className="form-row">
<div className="form-group col">
<label>Password</label>
<Field name="password" type="password" className={'form-control' + (errors.password && touched.password ? ' is-invalid' : '')} />
<ErrorMessage name="password" component="div" className="invalid-feedback" />
</div>
<div className="form-group col">
<label>Confirm Password</label>
<Field name="confirmPassword" type="password" className={'form-control' + (errors.confirmPassword && touched.confirmPassword ? ' is-invalid' : '')} />
<ErrorMessage name="confirmPassword" component="div" className="invalid-feedback" />
</div>
</div>
<div className="form-group">
<button type="submit" disabled={isSubmitting} className="btn btn-primary">
{isSubmitting && <span className="spinner-border spinner-border-sm mr-1"></span>}
Save
</button>
<Link to={isAddMode ? '.' : '..'} className="btn btn-link">Cancel</Link>
</div>
</Form>
);
}}
</Formik>
);
}
Example #22
Source File: ProductAddEdit.js From react-sample-projects with MIT License | 4 votes |
ProductAddEdit = () => {
const categories = useSelector(state => state.product.categories);
const dispatch = useDispatch();
const navigate = useNavigate();
const initialValues = {
title: '',
price: '',
category: '',
description: '',
image: '',
};
const validationSchema = yup.object({
title: yup.string().required(),
price: yup.number().required(),
category: yup.string().required(),
description: yup.string().required(),
image: yup.string().url().required(),
});
const onFormSubmit = (values, actions) => {
actions.setSubmitting(false);
dispatch(addNewProduct(values));
navigate('/');
};
useEffect(() => {
dispatch(fetchCategories());
return () => {};
}, [dispatch]);
return (
<Box boxShadow="base" m={'auto'} width="clamp(300px, 60%, 100%)">
<Formik
initialValues={initialValues}
onSubmit={onFormSubmit}
validationSchema={validationSchema}
>
{props => (
<Form noValidate>
<VStack p={3} m="3">
<Box fontWeight="semibold" mt="1" as="h2" textAlign="left">
Add Product
</Box>
<Field name="title">
{({ field, form }) => (
<FormControl
isRequired
isInvalid={form.errors.title && form.touched.title}
>
<FormLabel htmlFor="title">Enter Title</FormLabel>
<Input
{...field}
type="text"
id="title"
placeholder="Enter Title"
/>
<ErrorMessage
name="title"
component={FormErrorMessage}
></ErrorMessage>
</FormControl>
)}
</Field>
<Field name="price">
{({ field, form }) => (
<FormControl
isRequired
isInvalid={form.errors.price && form.touched.price}
>
<FormLabel>Enter price</FormLabel>
<Input type="number" placeholder="Enter price" {...field} />
<ErrorMessage
name="price"
component={FormErrorMessage}
></ErrorMessage>
</FormControl>
)}
</Field>
<Field name="category">
{({ field, form }) => (
<FormControl
name="category"
isRequired
isInvalid={form.errors.category && form.touched.category}
>
<FormLabel>Enter category</FormLabel>
<Select placeholder="Select category" {...field}>
{categories.map((category, index) => (
<option key={index}>{category}</option>
))}
</Select>
<ErrorMessage
name="category"
component={FormErrorMessage}
></ErrorMessage>
</FormControl>
)}
</Field>
<Field name="description">
{({ field, form }) => (
<FormControl
name="description"
isRequired
isInvalid={
form.errors.description && form.touched.description
}
>
<FormLabel>Enter description</FormLabel>
<Textarea
{...field}
id="description"
placeholder="Enter description"
></Textarea>
<ErrorMessage
name="description"
component={FormErrorMessage}
></ErrorMessage>
</FormControl>
)}
</Field>
<Field name="image">
{({ field, form }) => (
<FormControl
name="image"
isRequired
isInvalid={form.errors.image && form.touched.image}
>
<FormLabel>Enter image</FormLabel>
<Input
type="url"
placeholder="Enter image url"
{...field}
/>
<ErrorMessage
name="image"
component={FormErrorMessage}
></ErrorMessage>
</FormControl>
)}
</Field>
<Button
mt={4}
colorScheme="teal"
type="submit"
isLoading={props.isSubmitting}
>
Add Product
</Button>
</VStack>
</Form>
)}
</Formik>
</Box>
);
}
Example #23
Source File: Update.jsx From react-signup-verification-boilerplate with MIT License | 4 votes |
function Update({ history }) {
const user = accountService.userValue;
const initialValues = {
title: user.title,
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
password: '',
confirmPassword: ''
};
const validationSchema = Yup.object().shape({
title: Yup.string()
.required('Title is required'),
firstName: Yup.string()
.required('First Name is required'),
lastName: Yup.string()
.required('Last Name is required'),
email: Yup.string()
.email('Email is invalid')
.required('Email is required'),
password: Yup.string()
.min(6, 'Password must be at least 6 characters'),
confirmPassword: Yup.string()
.when('password', (password, schema) => {
if (password) return schema.required('Confirm Password is required');
})
.oneOf([Yup.ref('password')], 'Passwords must match')
});
function onSubmit(fields, { setStatus, setSubmitting }) {
setStatus();
accountService.update(user.id, fields)
.then(() => {
alertService.success('Update successful', { keepAfterRouteChange: true });
history.push('.');
})
.catch(error => {
setSubmitting(false);
alertService.error(error);
});
}
const [isDeleting, setIsDeleting] = useState(false);
function onDelete() {
if (confirm('Are you sure?')) {
setIsDeleting(true);
accountService.delete(user.id)
.then(() => alertService.success('Account deleted successfully'));
}
}
return (
<Formik initialValues={initialValues} validationSchema={validationSchema} onSubmit={onSubmit}>
{({ errors, touched, isSubmitting }) => (
<Form>
<h1>Update Profile</h1>
<div className="form-row">
<div className="form-group col">
<label>Title</label>
<Field name="title" as="select" className={'form-control' + (errors.title && touched.title ? ' is-invalid' : '')}>
<option value=""></option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss">Miss</option>
<option value="Ms">Ms</option>
</Field>
<ErrorMessage name="title" component="div" className="invalid-feedback" />
</div>
<div className="form-group col-5">
<label>First Name</label>
<Field name="firstName" type="text" className={'form-control' + (errors.firstName && touched.firstName ? ' is-invalid' : '')} />
<ErrorMessage name="firstName" component="div" className="invalid-feedback" />
</div>
<div className="form-group col-5">
<label>Last Name</label>
<Field name="lastName" type="text" className={'form-control' + (errors.lastName && touched.lastName ? ' is-invalid' : '')} />
<ErrorMessage name="lastName" component="div" className="invalid-feedback" />
</div>
</div>
<div className="form-group">
<label>Email</label>
<Field name="email" type="text" className={'form-control' + (errors.email && touched.email ? ' is-invalid' : '')} />
<ErrorMessage name="email" component="div" className="invalid-feedback" />
</div>
<h3 className="pt-3">Change Password</h3>
<p>Leave blank to keep the same password</p>
<div className="form-row">
<div className="form-group col">
<label>Password</label>
<Field name="password" type="password" className={'form-control' + (errors.password && touched.password ? ' is-invalid' : '')} />
<ErrorMessage name="password" component="div" className="invalid-feedback" />
</div>
<div className="form-group col">
<label>Confirm Password</label>
<Field name="confirmPassword" type="password" className={'form-control' + (errors.confirmPassword && touched.confirmPassword ? ' is-invalid' : '')} />
<ErrorMessage name="confirmPassword" component="div" className="invalid-feedback" />
</div>
</div>
<div className="form-group">
<button type="submit" disabled={isSubmitting} className="btn btn-primary mr-2">
{isSubmitting && <span className="spinner-border spinner-border-sm mr-1"></span>}
Update
</button>
<button type="button" onClick={() => onDelete()} className="btn btn-danger" style={{ width: '75px' }} disabled={isDeleting}>
{isDeleting
? <span className="spinner-border spinner-border-sm"></span>
: <span>Delete</span>
}
</button>
<Link to="." className="btn btn-link">Cancel</Link>
</div>
</Form>
)}
</Formik>
)
}
Example #24
Source File: Update.js From shopping-cart-fe with MIT License | 4 votes |
Update = (props) => {
const [loading, setLoading] = useState(false);
const [color, setColor] = useState(props.color.color);
const [confirmDelete, setConfirmDelete] = useState(false);
const [confirmLogout, setConfirmLogout] = useState(false);
const uploadImage = (e) => {
const files = e.target.files;
setLoading(true);
const data = new FormData();
data.append('file', files[0]);
data.append('upload_preset', 'shopping-cart-logo');
axios
.post('https://api.cloudinary.com/v1_1/dnsl4nbz4/image/upload', data)
.then((res) => {
props.logoUpload(res.data.secure_url);
});
setLoading(false);
};
return (
<div className='profileWrapper' data-testid='updateProfileWrapper'>
<h1 className='profileHeader' data-testid='updateProfileMainHeader' >Profile</h1>
<div className='imageColorWrapper' data-testid='updateProfileSecondaryWrapper'>
<div className='image-color' data-testid='updateProfileColorWrappers'>
<div className='logoDiv' data-testid='updateProfileLogoWrappers'>
<label className='logoChangeButton' htmlFor='uploadButton'>
Change logo
</label>
{loading ? (
<p>Loading...</p>
) : (
<img
style={{ height: '100px' }}
alt='logo'
src={props.logo.logo}
/>
)}
<input data-testid='updateUploadImageButton' id='uploadButton' type='file' onChange={uploadImage} />
</div>
<div className='colorDiv' >
<h3 className='colorHeader'>Brand Color</h3>
<TwitterPicker
className='twitterPicker'
color={color}
onChangeComplete={(color) => {
setColor(color.hex);
props.colorUpload(color.hex);
}}
/>
<div
style={{
margin: '1rem',
backgroundColor: props.color.color,
height: '50px',
width: '50%',
transition: 'ease all 500ms',
}}></div>
</div>
</div>
<Form className='profileForm' >
<div className='formTop' data-testid='updateProfileTopDiv'>
<div className='formTopLeft' data-testid='updateProfileLeftDiv'>
<label htmlFor='business name'data-testid='updateProfileBusName' >Business Name*</label>
<br />
<Field
name='businessName'
type='text'
value={props.values.businessName}
placeholder={props.address}
className='formInputFields'
/>
{props.touched.businessName && props.errors.businessName && (
<p className='formErrorHandling'>enter, please</p>
)}
<br />
<label htmlFor='owner name' data-testid='updateProfileOwnerName'>Owner Name*</label>
<br />
<Field
name='ownerName'
type='text'
value={props.values.ownerName}
placeholder={props.ownerName}
className='formInputFields'
/>
{props.touched.ownerName && props.errors.ownerName && (
<p className='formErrorHandling'>enter, please</p>
)}
<br />
<label htmlFor='address'>Address*</label>
<br />
<Field
name='address'
type='text'
value={props.values.address}
placeholder={props.address}
className='formInputFields'
/>
{props.touched.address && props.errors.address && (
<p className='formErrorHandling'>address, please</p>
)}
<br />
<label htmlFor='owner name'>Second Address</label>
<br />
<Field
name='secondAddress'
type='text'
value={props.values.secondAddress}
placeholder={props.secondAddress}
className='formInputFields'
/>
{props.touched.secondAddress && props.errors.secondAddress && (
<p className='formErrorHandling'>enter if needed</p>
)}
</div>
<div className='formTopRight'>
<label htmlFor='city'>City*</label>
<br />
<Field
name='city'
type='text'
value={props.values.city}
placeholder={props.city}
className='formInputFields'
/>
{props.touched.city && props.errors.city && (
<p className='formErrorHandling'>City required</p>
)}
<br />
<label htmlFor='state'>State*</label>
<br />
<Field
name='state'
type='text'
value={props.values.state}
placeholder={props.state}
className='formInputFields'
/>
{props.touched.state && props.errors.state && (
<p className='formErrorHandling'>enter State</p>
)}
<br />
<label htmlFor='zip code'>Zip Code*</label>
<br />
<Field
name='zipcode'
type='number'
maxLength={5}
placeholder={props.zipcode}
value={props.values.zipcode}
className='formInputFields'
/>
<ErrorMessage name='zipcode'>
{(msg) => <div className='formErrorHandling'>{msg}</div>}
</ErrorMessage>
</div>
</div>
<label htmlFor='store hours'>Store Hours*</label>
<br />
<Field
name='hours'
type='text'
value={props.values.hours}
placeholder={props.hours}
className='formInputFields'
/>
{props.touched.hours && props.errors.hours && (
<p className='formErrorHandling'>enter Hours of Operation</p>
)}
<br />
<label htmlFor='curbside hours'>Curbside Pickup Hours</label>
<br />
<Field
name='curbHours'
type='text'
value={props.values.curbHours}
placeholder={props.curbHours}
className='formInputFields'
/>
{props.touched.curbHours && props.errors.curbHours && (
<p className='formErrorHandling'>enter Curbside hours</p>
)}
<br />
<div className='buttonDiv'>
<button className='updateProfileButton' type='submit'>
Update Profile
</button>
<p className={confirmDelete ? 'showMe' : 'hidden'}>
Are you sure you want to delete your store information?
</p>
<p className={confirmLogout ? 'showMe' : 'hidden'}>
Are you sure you want to logout?
</p>
<div className='logoutDelete'>
<button
className={
confirmLogout || confirmDelete ? 'hidden' : 'showMeLogout'
}
onClick={() => {
setConfirmLogout(true);
}}>
Logout
</button>
<button
className={confirmLogout ? 'showMe' : 'hidden'}
onClick={() => {
localStorage.clear();
history.push('/');
}}>
Confirm Logout
</button>
<button
onClick={() => {
setConfirmDelete(!confirmDelete);
}}
className={!confirmDelete ? 'hidden' : 'showMe'}>
Don't delete my store!
</button>
<button
onClick={() => {
setConfirmLogout(!confirmLogout);
}}
className={!confirmLogout ? 'hidden' : 'showMe'}>
Don't log me out!
</button>
<button
onClick={() => {
setConfirmDelete(true);
}}
className={
confirmDelete || confirmLogout ? 'hidden' : 'showMe'
}>
Delete Store
</button>
<button
className={confirmDelete ? 'showMe' : 'hidden'}
onClick={(values) => {
props.deleteSellerInfo(values);
history.push('/welcome');
}}>
Confirm Deletion
</button>
</div>
</div>
</Form>
</div>
</div>
);
}
Example #25
Source File: ResetPassword.jsx From react-signup-verification-boilerplate with MIT License | 4 votes |
function ResetPassword({ history }) {
const TokenStatus = {
Validating: 'Validating',
Valid: 'Valid',
Invalid: 'Invalid'
}
const [token, setToken] = useState(null);
const [tokenStatus, setTokenStatus] = useState(TokenStatus.Validating);
useEffect(() => {
const { token } = queryString.parse(location.search);
// remove token from url to prevent http referer leakage
history.replace(location.pathname);
accountService.validateResetToken(token)
.then(() => {
setToken(token);
setTokenStatus(TokenStatus.Valid);
})
.catch(() => {
setTokenStatus(TokenStatus.Invalid);
});
}, []);
function getForm() {
const initialValues = {
password: '',
confirmPassword: ''
};
const validationSchema = Yup.object().shape({
password: Yup.string()
.min(6, 'Password must be at least 6 characters')
.required('Password is required'),
confirmPassword: Yup.string()
.oneOf([Yup.ref('password'), null], 'Passwords must match')
.required('Confirm Password is required'),
});
function onSubmit({ password, confirmPassword }, { setSubmitting }) {
alertService.clear();
accountService.resetPassword({ token, password, confirmPassword })
.then(() => {
alertService.success('Password reset successful, you can now login', { keepAfterRouteChange: true });
history.push('login');
})
.catch(error => {
setSubmitting(false);
alertService.error(error);
});
}
return (
<Formik initialValues={initialValues} validationSchema={validationSchema} onSubmit={onSubmit}>
{({ errors, touched, isSubmitting }) => (
<Form>
<div className="form-group">
<label>Password</label>
<Field name="password" type="password" className={'form-control' + (errors.password && touched.password ? ' is-invalid' : '')} />
<ErrorMessage name="password" component="div" className="invalid-feedback" />
</div>
<div className="form-group">
<label>Confirm Password</label>
<Field name="confirmPassword" type="password" className={'form-control' + (errors.confirmPassword && touched.confirmPassword ? ' is-invalid' : '')} />
<ErrorMessage name="confirmPassword" component="div" className="invalid-feedback" />
</div>
<div className="form-row">
<div className="form-group col">
<button type="submit" disabled={isSubmitting} className="btn btn-primary">
{isSubmitting && <span className="spinner-border spinner-border-sm mr-1"></span>}
Reset Password
</button>
<Link to="login" className="btn btn-link">Cancel</Link>
</div>
</div>
</Form>
)}
</Formik>
);
}
function getBody() {
switch (tokenStatus) {
case TokenStatus.Valid:
return getForm();
case TokenStatus.Invalid:
return <div>Token validation failed, if the token has expired you can get a new one at the <Link to="forgot-password">forgot password</Link> page.</div>;
case TokenStatus.Validating:
return <div>Validating token...</div>;
}
}
return (
<div>
<h3 className="card-header">Reset Password</h3>
<div className="card-body">{getBody()}</div>
</div>
)
}
Example #26
Source File: Register.jsx From react-signup-verification-boilerplate with MIT License | 4 votes |
function Register({ history }) {
const initialValues = {
title: '',
firstName: '',
lastName: '',
email: '',
password: '',
confirmPassword: '',
acceptTerms: false
};
const validationSchema = Yup.object().shape({
title: Yup.string()
.required('Title is required'),
firstName: Yup.string()
.required('First Name is required'),
lastName: Yup.string()
.required('Last Name is required'),
email: Yup.string()
.email('Email is invalid')
.required('Email is required'),
password: Yup.string()
.min(6, 'Password must be at least 6 characters')
.required('Password is required'),
confirmPassword: Yup.string()
.oneOf([Yup.ref('password'), null], 'Passwords must match')
.required('Confirm Password is required'),
acceptTerms: Yup.bool()
.oneOf([true], 'Accept Terms & Conditions is required')
});
function onSubmit(fields, { setStatus, setSubmitting }) {
setStatus();
accountService.register(fields)
.then(() => {
alertService.success('Registration successful, please check your email for verification instructions', { keepAfterRouteChange: true });
history.push('login');
})
.catch(error => {
setSubmitting(false);
alertService.error(error);
});
}
return (
<Formik initialValues={initialValues} validationSchema={validationSchema} onSubmit={onSubmit}>
{({ errors, touched, isSubmitting }) => (
<Form>
<h3 className="card-header">Register</h3>
<div className="card-body">
<div className="form-row">
<div className="form-group col">
<label>Title</label>
<Field name="title" as="select" className={'form-control' + (errors.title && touched.title ? ' is-invalid' : '')}>
<option value=""></option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss">Miss</option>
<option value="Ms">Ms</option>
</Field>
<ErrorMessage name="title" component="div" className="invalid-feedback" />
</div>
<div className="form-group col-5">
<label>First Name</label>
<Field name="firstName" type="text" className={'form-control' + (errors.firstName && touched.firstName ? ' is-invalid' : '')} />
<ErrorMessage name="firstName" component="div" className="invalid-feedback" />
</div>
<div className="form-group col-5">
<label>Last Name</label>
<Field name="lastName" type="text" className={'form-control' + (errors.lastName && touched.lastName ? ' is-invalid' : '')} />
<ErrorMessage name="lastName" component="div" className="invalid-feedback" />
</div>
</div>
<div className="form-group">
<label>Email</label>
<Field name="email" type="text" className={'form-control' + (errors.email && touched.email ? ' is-invalid' : '')} />
<ErrorMessage name="email" component="div" className="invalid-feedback" />
</div>
<div className="form-row">
<div className="form-group col">
<label>Password</label>
<Field name="password" type="password" className={'form-control' + (errors.password && touched.password ? ' is-invalid' : '')} />
<ErrorMessage name="password" component="div" className="invalid-feedback" />
</div>
<div className="form-group col">
<label>Confirm Password</label>
<Field name="confirmPassword" type="password" className={'form-control' + (errors.confirmPassword && touched.confirmPassword ? ' is-invalid' : '')} />
<ErrorMessage name="confirmPassword" component="div" className="invalid-feedback" />
</div>
</div>
<div className="form-group form-check">
<Field type="checkbox" name="acceptTerms" id="acceptTerms" className={'form-check-input ' + (errors.acceptTerms && touched.acceptTerms ? ' is-invalid' : '')} />
<label htmlFor="acceptTerms" className="form-check-label">Accept Terms & Conditions</label>
<ErrorMessage name="acceptTerms" component="div" className="invalid-feedback" />
</div>
<div className="form-group">
<button type="submit" disabled={isSubmitting} className="btn btn-primary">
{isSubmitting && <span className="spinner-border spinner-border-sm mr-1"></span>}
Register
</button>
<Link to="login" className="btn btn-link">Cancel</Link>
</div>
</div>
</Form>
)}
</Formik>
)
}
Example #27
Source File: AddEdit.jsx From react-formik-master-details-crud-example with MIT License | 4 votes |
function AddEdit({ history, match }) {
const { id } = match.params;
const isAddMode = !id;
const initialValues = {
title: '',
firstName: '',
lastName: '',
email: '',
role: '',
password: '',
confirmPassword: ''
};
const validationSchema = Yup.object().shape({
title: Yup.string()
.required('Title is required'),
firstName: Yup.string()
.required('First Name is required'),
lastName: Yup.string()
.required('Last Name is required'),
email: Yup.string()
.email('Email is invalid')
.required('Email is required'),
role: Yup.string()
.required('Role is required'),
password: Yup.string()
.concat(isAddMode ? Yup.string().required('Password is required') : null)
.min(6, 'Password must be at least 6 characters'),
confirmPassword: Yup.string()
.when('password', (password, schema) => {
if (password || isAddMode) return schema.required('Confirm Password is required');
})
.oneOf([Yup.ref('password')], 'Passwords must match')
});
function onSubmit(fields, { setStatus, setSubmitting }) {
setStatus();
if (isAddMode) {
createUser(fields, setSubmitting);
} else {
updateUser(id, fields, setSubmitting);
}
}
function createUser(fields, setSubmitting) {
userService.create(fields)
.then(() => {
alertService.success('User added', { keepAfterRouteChange: true });
history.push('.');
})
.catch(() => {
setSubmitting(false);
alertService.error(error);
});
}
function updateUser(id, fields, setSubmitting) {
userService.update(id, fields)
.then(() => {
alertService.success('User updated', { keepAfterRouteChange: true });
history.push('..');
})
.catch(error => {
setSubmitting(false);
alertService.error(error);
});
}
return (
<Formik initialValues={initialValues} validationSchema={validationSchema} onSubmit={onSubmit}>
{({ errors, touched, isSubmitting, setFieldValue }) => {
const [user, setUser] = useState({});
const [showPassword, setShowPassword] = useState(false);
useEffect(() => {
if (!isAddMode) {
// get user and set form fields
userService.getById(id).then(user => {
const fields = ['title', 'firstName', 'lastName', 'email', 'role'];
fields.forEach(field => setFieldValue(field, user[field], false));
setUser(user);
});
}
}, []);
return (
<Form>
<h1>{isAddMode ? 'Add User' : 'Edit User'}</h1>
<div className="form-row">
<div className="form-group col">
<label>Title</label>
<Field name="title" as="select" className={'form-control' + (errors.title && touched.title ? ' is-invalid' : '')}>
<option value=""></option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss">Miss</option>
<option value="Ms">Ms</option>
</Field>
<ErrorMessage name="title" component="div" className="invalid-feedback" />
</div>
<div className="form-group col-5">
<label>First Name</label>
<Field name="firstName" type="text" className={'form-control' + (errors.firstName && touched.firstName ? ' is-invalid' : '')} />
<ErrorMessage name="firstName" component="div" className="invalid-feedback" />
</div>
<div className="form-group col-5">
<label>Last Name</label>
<Field name="lastName" type="text" className={'form-control' + (errors.lastName && touched.lastName ? ' is-invalid' : '')} />
<ErrorMessage name="lastName" component="div" className="invalid-feedback" />
</div>
</div>
<div className="form-row">
<div className="form-group col-7">
<label>Email</label>
<Field name="email" type="text" className={'form-control' + (errors.email && touched.email ? ' is-invalid' : '')} />
<ErrorMessage name="email" component="div" className="invalid-feedback" />
</div>
<div className="form-group col">
<label>Role</label>
<Field name="role" as="select" className={'form-control' + (errors.role && touched.role ? ' is-invalid' : '')}>
<option value=""></option>
<option value="User">User</option>
<option value="Admin">Admin</option>
</Field>
<ErrorMessage name="role" component="div" className="invalid-feedback" />
</div>
</div>
{!isAddMode &&
<div>
<h3 className="pt-3">Change Password</h3>
<p>Leave blank to keep the same password</p>
</div>
}
<div className="form-row">
<div className="form-group col">
<label>
Password
{!isAddMode &&
(!showPassword
? <span> - <a onClick={() => setShowPassword(!showPassword)} className="text-primary">Show</a></span>
: <span> - {user.password}</span>
)
}
</label>
<Field name="password" type="password" className={'form-control' + (errors.password && touched.password ? ' is-invalid' : '')} />
<ErrorMessage name="password" component="div" className="invalid-feedback" />
</div>
<div className="form-group col">
<label>Confirm Password</label>
<Field name="confirmPassword" type="password" className={'form-control' + (errors.confirmPassword && touched.confirmPassword ? ' is-invalid' : '')} />
<ErrorMessage name="confirmPassword" component="div" className="invalid-feedback" />
</div>
</div>
<div className="form-group">
<button type="submit" disabled={isSubmitting} className="btn btn-primary">
{isSubmitting && <span className="spinner-border spinner-border-sm mr-1"></span>}
Save
</button>
<Link to={isAddMode ? '.' : '..'} className="btn btn-link">Cancel</Link>
</div>
</Form>
);
}}
</Formik>
);
}
Example #28
Source File: Signup.js From codeclannigeria-frontend with MIT License | 4 votes |
function Signup({ register, loading, error, errResponse, token, history }) {
const dispatch = useDispatch();
const passwordRef = useRef();
const confirmPasswordRef = useRef();
const [passwordDisplay, setpasswordDisplay] = useState({
password1: null,
password2: null,
});
// const togglePasswordToText = ref => {
// setpasswordDisplay(!passwordDisplay);
// ref.current.firstChild.type === 'password'
// ? (ref.current.firstChild.type = 'text')
// : (ref.current.firstChild.type = 'password');
// };
const togglePasswordToText = ref => {
// console.log(passwordDisplay.confirmPassword);
const passwordNode = ref.current.childNodes[0];
const nodeName = passwordNode.name;
// console.log(nodeName);
if (passwordNode.type === 'password') {
passwordNode.type = 'text';
const tempState = { ...passwordDisplay, [nodeName]: true };
setpasswordDisplay(tempState);
} else {
passwordNode.type = 'password';
const tempState = { ...passwordDisplay, [nodeName]: false };
setpasswordDisplay(tempState);
}
};
useEffect(() => {
dispatch({ type: 'AUTH_RESET' });
}, [dispatch]);
const openNotification = () => {
notification.success({
message: 'Registration Successful',
description: 'Kindly check your email for further instructions',
});
};
useEffect(() => {
if (checkAuth()) {
history.push('/dashboard');
}
}, [history]);
useEffect(() => {
if (token) {
openNotification();
history.push('/email-verification-sent/');
}
}, [token, history, dispatch]);
useEffect(() => {
if (error) {
message.error(errResponse);
}
}, [error, errResponse]);
const errorClassNames = 'border input border-danger';
const validClassNames = 'border input border-green';
// const regex = /^[a-z]([-']?[a-z]+)*( [a-z]([-']?[a-z]+)*)+$/i;
return (
<Formik
initialValues={{
firstName: '',
lastName: '',
email: '',
password1: '',
password2: '',
}}
validationSchema={Yup.object({
firstName: Yup.string()
.min(3, 'Too short')
.max(64, 'Must be 64 characters or less')
.required('Enter your first name i.e John '),
lastName: Yup.string()
.min(3, 'Too short')
.max(64, 'Must be 64 characters or less')
.required('Enter your Last name i.e Doe '),
email: Yup.string()
.email('Invalid email address')
.required('Enter your email address'),
password1: Yup.string().required('Enter a password of your choice'),
password2: Yup.string()
.required('Confirm the password entered above')
.oneOf([Yup.ref('password1'), null], 'Passwords must match'),
})}
onSubmit={(values, { setSubmitting }) => {
setSubmitting(true);
const tempValues = { ...values };
// const nameArray = tempValues.fullName.split(' ');
// tempValues.firstName = nameArray[0];
// tempValues.lastName = nameArray[1];
tempValues.password = tempValues.password1;
// delete tempValues.fullName;
delete tempValues.password1;
delete tempValues.password2;
register(tempValues);
}}
>
{({ errors, touched, isSubmitting }) => (
<SignupStyled>
<div>
<div class="main">
<div class="left">
<div class="logo">
<div>
<Link to="/" className="image-link">
<img
className="img-fluid"
src={codeClanLogo}
alt="Code clan"
/>
</Link>
</div>
</div>
<div class="titles"> Create your account </div>
<Form>
{/* <AlertComponent variant="danger" text={errResponse} /> */}
<label htmlFor="firstName">
First Name <span class="text-danger">*</span>
</label>
<div class="block">
<Field
name="firstName"
id="firstName"
className={
touched.firstName && errors.firstName
? errorClassNames
: validClassNames
}
type="text"
/>
<span>
<i class="far fa-user"></i>
</span>
</div>
<div className="d-block text-monospace text-danger small-text">
<ErrorMessage name="firstName" className="d-block" />
</div>
<label htmlFor="lastName">
Last Name <span class="text-danger">*</span>
</label>
<div class="block">
<Field
name="lastName"
id="lastName"
className={
touched.lastName && errors.lastName
? errorClassNames
: validClassNames
}
type="text"
/>
<span>
<i class="far fa-user"></i>
</span>
</div>
<div className="d-block text-monospace text-danger small-text">
<ErrorMessage name="lastName" className="d-block" />
</div>
<label htmlFor="email">
E-mail <span class="text-danger">*</span>
</label>
<div className="block">
<Field
id="email"
type="email"
name="email"
className={
touched.email && errors.email
? errorClassNames
: validClassNames
}
/>
<span>
<i class="fa fa-at" aria-hidden="true"></i>
</span>
</div>
<div className="d-block text-monospace text-danger small-text">
<ErrorMessage name="email" className="d-block" />
</div>
<label htmlFor="password1">
Password <span class="text-danger">*</span>
</label>
<div class="block" ref={passwordRef}>
<Field
id="password1"
name="password1"
className={
touched.password1 && errors.password1
? errorClassNames
: validClassNames
}
type="password"
/>
<span onClick={() => togglePasswordToText(passwordRef)}>
{/* <i class="fa fa-eye" aria-hidden="true"></i> */}
{passwordDisplay.password1 ? (
<i class="fas fa-eye-slash"></i>
) : (
<i class="far fa-eye"></i>
)}
</span>
</div>
<div className="d-block text-monospace text-danger small-text">
<ErrorMessage name="password1" className="d-block" />
</div>
<label htmlFor="password2">
Confirm Password <span class="text-danger">*</span>
</label>
<div class="block" ref={confirmPasswordRef}>
<Field
id="password2"
name="password2"
className={
touched.password2 && errors.password2
? errorClassNames
: validClassNames
}
type="password"
/>
<span
onClick={() => togglePasswordToText(confirmPasswordRef)}
>
{passwordDisplay.password2 ? (
<i class="fas fa-eye-slash"></i>
) : (
<i class="far fa-eye"></i>
)}
{/* <i class="fa fa-eye" aria-hidden="true"></i> */}
</span>
</div>
<div className="d-block text-monospace text-danger small-text">
<ErrorMessage name="password2" className="d-block" />
</div>
<button
disabled={loading}
className={loading ? 'btn btn-light w-100' : 'submit'}
type="submit"
>
{!loading ? (
'get started'
) : (
<span>
<Spinner animation="border" variant="primary" />
</span>
)}
</button>
<div class="centralize" style={{ lineHeight: '2em' }}>
<p>
Already have an account? <Link to="/login">Log in</Link>
</p>
</div>
</Form>
</div>
<div class="right">
<img
alt="Login animation"
src={loginAmico}
style={{ height: '50%' }}
/>
<p class="small">CODECLAN NIGERIA</p>
<p class="normal">
Join us and take your programming career to the next level
</p>
</div>
</div>
</div>
</SignupStyled>
)}
</Formik>
);
}
Example #29
Source File: ResetPassword.js From codeclannigeria-frontend with MIT License | 4 votes |
function ResetPassword({ history, location }) {
const dispatch = useDispatch();
const authState = useSelector(state => state.auth);
const { loading, error, errResponse, token } = authState;
const [passwordDisplay, setpasswordDisplay] = useState({
password: null,
confirmPassword: null,
});
const [resetToken, setresetToken] = useState();
const [resetEmail, setResetEmail] = useState();
const passwordRef = useRef();
const confirmPasswordRef = useRef();
const togglePasswordToText = ref => {
const passwordNode = ref.current.childNodes[1];
const nodeName = passwordNode.name;
if (passwordNode.type === 'password') {
passwordNode.type = 'text';
const tempState = { ...passwordDisplay, [nodeName]: true };
setpasswordDisplay(tempState);
} else {
passwordNode.type = 'password';
const tempState = { ...passwordDisplay, [nodeName]: false };
setpasswordDisplay(tempState);
}
};
const errorClassNames = 'border input border-danger';
const validClassNames = 'border input border-green';
useEffect(() => {
dispatch({ type: 'AUTH_RESET' });
}, [dispatch]);
const openNotification = () => {
notification.success({
message: 'Password Reset Successful',
description: 'You can login into your account with the new password',
});
};
useEffect(() => {
if (token) {
openNotification();
// history.push('/email-verification-sent/');
}
}, [token, dispatch]);
useEffect(() => {
if (error) {
message.error(errResponse);
}
}, [error, errResponse]);
useEffect(() => {
const UrlQueryStrings = location.search;
const queryValues = queryString.parse(UrlQueryStrings);
const token = queryValues.token || undefined;
const email = queryValues.email || undefined;
setResetEmail(email);
setresetToken(token);
// if (!token || !email) {
// history.push('/');
// }
}, [location.search]);
return (
<React.Fragment>
<Navbar />
<Formik
initialValues={{ password: '', confirmPassword: '' }}
validationSchema={Yup.object({
password: Yup.string().required('Enter a password of your choice'),
confirmPassword: Yup.string()
.required('Confirm the password entered above')
.oneOf([Yup.ref('password'), null], 'Passwords must match'),
})}
onSubmit={(values, { setSubmitting }) => {
const userData = {
newPassword: values.password,
token: resetToken,
email: resetEmail,
};
dispatch(resetPasswordRequestAction(userData));
}}
>
{({ errors, touched, isSubmitting }) => (
<ForgotPasswordStyled>
<div className="container-fluid">
<div className="row justify-content-center align-items-center vh-100">
<div className="col-lg-5 col-sm-6 col-md-6 align-self-center">
<Form className="form-container ">
<div className="form-group px-3">
<div className="form-text mb-4">
<h1 className="text-center mb-2">
Reset your Password
</h1>
<p className="text-center mt-4">
Enter the new password of your choice
</p>
</div>
<div className="input-group mb-4" ref={passwordRef}>
<div className="input-group-prepend">
<span className="input-group-text">
<i class="fas fa-lock"></i>
</span>
</div>
<Field
type="password"
className={`form-control ${
touched.password && errors.password
? errorClassNames
: validClassNames
}`}
name="password"
aria-label="forget-Email"
aria-describedby="forget-Email"
/>
<div class="input-group-append">
<span
class="input-group-text"
name="password"
onClick={() => togglePasswordToText(passwordRef)}
>
{passwordDisplay.password ? (
<i class="fas fa-eye-slash"></i>
) : (
<i class="far fa-eye"></i>
)}
</span>
</div>
</div>
<div className="d-block text-monospace text-danger small-text">
<ErrorMessage name="password" className="d-block" />
</div>
<div
className="input-group mb-4"
ref={confirmPasswordRef}
>
<div className="input-group-prepend">
<span
name="confirmPassword"
className="input-group-text"
>
<i class="fas fa-lock"></i>
</span>
</div>
<Field
type="password"
className={`form-control ${
touched.confirmPassword && errors.confirmPassword
? errorClassNames
: validClassNames
}`}
name="confirmPassword"
/>
<div class="input-group-append">
<span
class="input-group-text"
onClick={() =>
togglePasswordToText(confirmPasswordRef)
}
>
{passwordDisplay.confirmPassword ? (
<i class="fas fa-eye-slash"></i>
) : (
<i class="far fa-eye"></i>
)}
</span>
</div>
</div>
<div className="d-block text-monospace text-danger small-text">
<ErrorMessage
name="confirmPassword"
className="d-block"
/>
</div>
<button
type="submit"
disabled={loading}
className={
loading ? 'btn btn-primary w-100 border-3' : 'submit'
}
>
{!loading ? (
'Submit'
) : (
<span className="text-small">
<Spinner animation="border" variant="primary" />
</span>
)}
</button>
<Link className="text-decoration-none" to="/login">
<p className="text-center mt-5">
<span>
<i className="fas fa-chevron-left"></i>
</span>{' '}
Back to Login
</p>
</Link>
</div>
</Form>
</div>
{/*
<div className="col-lg-8 image-container ">
<img
className="img-fluid"
style={{ width: '50%' }}
src={ForgotPasswordImage}
alt="Forgot password"
/>
<p class="title">CODECLAN NIGERIA</p>
<p class="normal">
Forgot your password? Input your email so you reset your
password
</p>
</div> */}
</div>
</div>
</ForgotPasswordStyled>
)}
</Formik>
</React.Fragment>
);
}