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 vote down vote up
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: Feedback.js    From Simplify-Testing-with-React-Testing-Library with MIT License 5 votes vote down vote up
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 #3
Source File: form.js    From proof-of-humanity-web with MIT License 5 votes vote down vote up
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 #4
Source File: Form.js    From codeclannigeria-frontend with MIT License 5 votes vote down vote up
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 #5
Source File: ForgotPassword.jsx    From react-signup-verification-boilerplate with MIT License 5 votes vote down vote up
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 #6
Source File: Login.jsx    From react-signup-verification-boilerplate with MIT License 5 votes vote down vote up
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: ReminderForm.js    From jc-calendar with MIT License 5 votes vote down vote up
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 #8
Source File: index.js    From realworld with MIT License 5 votes vote down vote up
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 #9
Source File: index.js    From realworld with MIT License 5 votes vote down vote up
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 #10
Source File: index.js    From realworld with MIT License 5 votes vote down vote up
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>
            &nbsp;&nbsp;
            <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 #11
Source File: TextField.js    From real-frontend with GNU General Public License v3.0 5 votes vote down vote up
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 #12
Source File: FormField.jsx    From react-chatengine-demo with MIT License 5 votes vote down vote up
FormField = ({ name, label, type = 'text' }) => (
  <label>
    {label}
    <Field name={name} type={type} />
    <ErrorMessage className="error" component="div" name={name} />
  </label>
)
Example #13
Source File: FormLayout.js    From umami with MIT License 5 votes vote down vote up
FormError = ({ name }) => {
  return <ErrorMessage name={name}>{msg => <ErrorTag msg={msg} />}</ErrorMessage>;
}
Example #14
Source File: Update.js    From shopping-cart-fe with MIT License 4 votes vote down vote up
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 #15
Source File: WelcomeScreen.js    From shopping-cart-fe with MIT License 4 votes vote down vote up
WelcomeScreen = (props) => {
  return (
    <div className='welcomeForm' data-testid='welcomeFormWrapper'>
      <img src={logo} alt='logo' />
      <h1 data-testid='welcomeHeader'>Welcome</h1>
      <h2 data-testid='secondaryWelcomeHeader'>
        To finish the account creation process fill out the forms below
      </h2>
      <Form className='formContainer' data-testid='welcomeForm'>
        <main className='sectionContainer' data-testid='welcomeMainSection'>
          <section className='firstSection' data-testid='welcomeFirstSection'>
            <section className='business' data-testid='welcomeSecondSection'>
              <label
                htmlFor='businessName'
                className='label'
                data-testid='businessName'>
                Business Name
              </label>
              <Field
                name='businessName'
                type='text'
                value={props.values.businessName}
                placeholder='Business name'
                className='field'
              />
              {props.touched.businessName && props.errors.businessName && (
                <p className='error'>Business Name is required</p>
              )}
            </section>
            <section className='rest'>
              <section className='firstHalf'>
                <label
                  htmlFor='ownerName'
                  className='label'
                  data-testid='ownerName'>
                  Owner Name
                </label>
                <Field
                  name='ownerName'
                  type='text'
                  value={props.values.ownerName}
                  placeholder='Owner name'
                  className='field'
                />
                {props.touched.ownerName && props.errors.ownerName && (
                  <p className='error'>Owner Name is required</p>
                )}
                <label
                  htmlFor='address'
                  className='label'
                  data-testid='address'>
                  Address
                </label>
                <Field
                  name='address'
                  type='text'
                  value={props.values.address}
                  placeholder='Add address'
                  className='field'
                />
                {props.touched.address && props.errors.address && (
                  <p className='error'>Address is required</p>
                )}
                <label
                  htmlFor='secondAddress'
                  className='label'
                  data-testid='secondAddress'>
                  Second Address
                </label>
                <Field
                  name='secondAddress'
                  type='text'
                  value={props.values.secondAddress}
                  placeholder='Add second address (if needed)'
                  className='field'
                />
              </section>
              <section className='secondHalf'>
                <label htmlFor='city' className='label' data-testid='city'>
                  City
                </label>
                <Field
                  name='city'
                  type='text'
                  value={props.values.city}
                  placeholder='Add city'
                  className='field'
                />
                {props.touched.city && props.errors.city && (
                  <p className='error'>City is required</p>
                )}
                <label htmlFor='state' className='label' data-testid='state'>
                  State
                </label>
                <Field
                  name='state'
                  type='text'
                  value={props.values.state}
                  placeholder='Add state '
                  className='field'
                />
                {props.touched.state && props.errors.state && (
                  <p className='error'>State is required</p>
                )}
                <label htmlFor='zipcode' className='label' data-testid='zip'>
                  Zip Code
                </label>
                <Field
                  name='zipcode'
                  type='text'
                  maxLength={5}
                  placeholder='Add zipcode'
                  value={props.values.zipcode}
                  className='field'
                />
                <ErrorMessage name='zipcode'>
                  {(msg) => <div className='error'>{msg}</div>}
                </ErrorMessage>
              </section>
            </section>
          </section>
          <section className='secondSection'>
            <label htmlFor='hours' className='label' data-testid='storeHours'>
              Store Hours
            </label>
            <Field
              name='hours'
              type='text'
              value={props.values.hours}
              placeholder='Add Hours of Operation'
              className='field'
            />
            {props.touched.hours && props.errors.hours && (
              <p className='error'>Enter Hours of Operation</p>
            )}
            <label htmlFor='curbHours' className='label' data-testid='curbside'>
              Curbside Pickup Hours
            </label>
            <Field
              name='curbHours'
              type='text'
              value={props.values.curbHours}
              placeholder='Add curbside hours'
              className='field'
            />
            {props.touched.curbHours && props.errors.curbHours && (
              <p className='error'>Enter Curbside hours</p>
            )}
          </section>
        </main>
        <button
          className='submitButton'
          type='submit'
          data-testid='welcomeAddInfoButton'>
          Add Information
        </button>
      </Form>
    </div>
  );
}
Example #16
Source File: FormikJobForm.js    From react-powerhouse with MIT License 4 votes vote down vote up
function FormikJobForm(props) {

    return (
        <Formik
            initialValues={{
                'firstname': '',
                'lastname': '',
                'email': '',
                'phone': '',
                'location': '',
                'current_employer': '',
                'current_role': '',
                'role_description': '',
                'experience': 0,
                'skills': '',
                'include_portfolio': false,
                'include_social': false
            }}
            onSubmit={values => console.log(values)}
            validate={values => {
                let error = {};
                if (values.firstname === 'Admin') {
                    error['firstname'] = 'You cannot use this';
                }
                return error;
            }}
        >
            {({values}) => (
                <Form>
                    { console.log('render') }
                    <section>
                        <h4>Personal Information</h4>
                        <br />
                        <div>
                            <label htmlFor="firstname">First Name</label>
                            <Field required type="text" id="firstname" name="firstname" />
                            <ErrorMessage name="firstname" component="span" />
                        </div>
                        <div>
                            <label htmlFor="lastname">Last Name</label>
                            <Field required type="text" id="lastname" name="lastname" />
                        </div>
                        <div>
                            <label htmlFor="email">Email Address</label>
                            <Field type="email" id="email" name="email" />
                        </div>
                        <div>
                            <label htmlFor="phone">Phone Number</label>
                            <Field type="text" id="phone" name="phone" />
                        </div>
                        <div>
                            <label htmlFor="location">Location</label>
                            <Field type="text" id="location" name="location" />
                        </div>
                    </section>
                    <section>
                        <h4>Work Information</h4>
                        <br />
                        <div>
                            <label htmlFor="current_employer">Current Employer</label>
                            <Field type="text" id="current_employer" name="current_employer" />
                        </div>
                        <div>
                            <label htmlFor="current_role">Current Role</label>
                            <Field type="text" id="current_role" name="current_role" />
                        </div>
                        <div>
                            <label htmlFor="role_description">Role Description</label>
                            <Field type="text" id="role_description" name="role_description" />
                        </div>
                        <div>
                            <label htmlFor="experience">Total Years of Experience</label>
                            <Field type="text" id="experience" name="experience" />
                        </div>
                        <div>
                            <label htmlFor="skills">Skills</label>
                            <Field type="text" id="skills" name="skills" />
                        </div>
                    </section>
                    <section>
                        <h4>Social Medial Links</h4>
                        <br />
                        <br />
                        <div>
                            <label>
                                <Field
                                    className="filled-in"
                                    type="checkbox"
                                    name="include_portfolio"
                                    id="include_portfolio"/>
                                <span>Include Portfolio Links?</span>
                            </label>
                        </div>
                        <br />
                        <div>
                            <label>
                                <Field
                                    className="filled-in"
                                    type="checkbox"
                                    name="include_social"
                                    id="include_social"/>
                                <span>Include Social Media Links?</span>
                            </label>
                        </div>
                        <br />
                        { values['include_portfolio'] && <div>
                            <label htmlFor="portfolio_links">Portfolio links</label>
                            <Field type="text" id="portfolio_links" name="portfolio_links" />
                        </div>}
                        { values['include_social'] && <div>
                            <label htmlFor="social_media_links">Social Media Links</label>
                            <Field type="text" id="social_media_links" name="social_media_links" />
                        </div>}
                        
                    </section>
                    <section>
                        <h4>Uploads</h4>
                        <br />
                        <div>
                            <label htmlFor="resume">Select Resume</label>
                            <br />
                            <input type="file" id="resume" />
                        </div>
                        <br /><br />
                        <div>
                            <label htmlFor="cover_letter">Select Cover Letter</label>
                            <br />
                            <input type="file" id="cover_letter" />
                        </div>
                    </section>
                    <br /><br />
                    <button type="submit" className="btn">Submit Form</button>
                </Form>
            )}
        </Formik>
    )
}
Example #17
Source File: index.js    From certificate-generator with MIT License 4 votes vote down vote up
FormRegister = (props) => {

	/*Verifica se o acesso foi aprovado*/
  	const [ acessAproved, setAproved ] = useState(false)

  	/*Organizador do evento*/
  	const [ organizador, setOrganizador ] = useState('')

	const formik = useFormik({
		initialValues: {
			name: "",
			email: "",
			password: "",
			remember: true,
		},
		validationSchema: Yup.object().shape({
			name: Yup.string().required('Digite seu nome'),
			email: Yup.string().email('E-mail inválido').required('Digite seu e-mail'),
			password: Yup.string().min(4).required('Digite uma senha')
		})
	})

	const { handleSubmit, values } = formik

	/*JSON dos usuários*/
	const [ user, setUser ] = useState(users)

	const addNewUser = (name, email, password, avatar) => {

		setUser([
			...user, {
			name: name,
			email: email,
			password: password, 
			token: true,
			avatar: avatar
		}
		])

		setAproved(true)
		setOrganizador(name)
		message.success('Conta criada com sucesso')
	}

	/*Função acionada após criar a conta com o formulário*/
	const actionButton = () => {
			
		if(!values.name || !values.email || !values.password) {
			message.warning('Por favor, preencha todos os campos') 

		} else {
			
			/*Verificando se já existe um usuário cadastrado*/
			let listEmails = []

			user.map(itemJson => {
				listEmails.push(itemJson.email)
			})

			/*Se o e-mail digitado pelo usuário pelo usuário ainda não está no JSON de usuários*/
			if(!listEmails.includes(values.email)) {
				addNewUser(values.name, values.email, values.password, " ")

			} else {
				message.warning('Esta conta já existe')
			}
		}
	}

	/*Função acionada após o login com o Google*/
	const responseGoogle = response => {

		/*Verificando se já existe um usuário cadastrado*/
		let listEmails = []

		user.map(itemJson => {
			listEmails.push(itemJson.email)
		})

		/*Se o e-mail digitado pelo usuário pelo usuário ainda não está no JSON de usuários*/
		if(!listEmails.includes(response.profileObj.email)) {
			addNewUser(response.profileObj.name, response.profileObj.email, true, response.profileObj.imageUrl)

		} else {
			message.warning('Esta conta já existe')
		}
	}

	return (
		<>
			<div className="form" style={{ display: acessAproved ?  'none' : 'block' }}>	
				<h1 className="title-cadastre">Cadastre uma conta já, é simples e rápido</h1>
				<div className="button-google" >
					<GoogleLogin 
						clientId="78039332386-46h93ebkr1bb708hqv47h410pdd89mj9.apps.googleusercontent.com"
						render={renderProps => (
						<button 	
							onClick={renderProps.onClick} disabled={renderProps.disabled} className="loginBtn loginBtn-google"> 
							Cadastrar com o Google </button>
						)}
						buttonText="Cadastrar com o Google"
						onSuccess={responseGoogle}
						onFailure={responseGoogle}
					/>
				</div>

				<p className="ou">OU</p>

				<FormikProvider value={formik}>
					<Form onSubmit={handleSubmit}>
						
						<Field 
							name="name" 
							type="text" 
							className="form-field"
							prefix={<UserOutlined className="site-form-item-icon" />}
							placeholder="Digite seu nome"
						/>
						<ErrorMessage 
							render={msg => <p className="msg-error" >{msg}</p>}
							name="name" />
						
						
						<Field 
							name="email" 
							type="text" 
							className="form-field" 
							prefix={<ScheduleOutlined className="site-form-item-icon" />}
							placeholder="Digite seu e-mail"
							
						/>
						<ErrorMessage 
							render={msg => <p className="msg-error" >{msg}</p>} 
							name="email" />
						
						
						<Field 
							name="password"
							type="password" 
							className="form-field" 
							placeholder="Digite uma senha"
							prefix={<LockOutlined className="site-form-item-icon" />}
						/>
						<ErrorMessage 
							render={msg => <p className="msg-error" >{msg}</p>} 
							name="password" />

						<Button 
							type="submit" 
							onClick={actionButton} 
							className="button"
							
						>Criar conta</Button>
					</Form>
				</FormikProvider>
			</div>
			{/*Renderizando a pagina de lista de eventos*/}
      		{ acessAproved && <ListEvents users={user} organizador={organizador}/>}
		</>
	);
}
Example #18
Source File: SubmitTask.js    From codeclannigeria-frontend with MIT License 4 votes vote down vote up
function SubmitTask(props) {
  const [submitted, setSubmitted] = useState(false);
  const { id } = props.match.params;
  const dispatch = useDispatch();
  const tasks = useSelector(state => state.tasks);
  const { error, errResponse, taskSubmit, loading } = tasks;

  const fetchData = useCallback(async () => {
    await dispatch(getSingleTaskAction(id));
  }, [dispatch, id]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  useEffect(() => {
    if (error) {
      message.error(errResponse);
    }
  }, [error, errResponse]);

  if (submitted && taskSubmit === 'success') {
    const data = {
      header: `Successfully sumitted Task #${id}`,
      description:
        'Your mentor will review your submission and will get back to you',
      backLink: '/dashboard/pending-task',
      id,
    };
    return <SuccessfulSubmission data={data} />;
  }
  const errorClassNames = 'border input border-danger';
  const validClassNames = 'border input border-green';
  return (
    <SubmitTaskStyled>
      <div className="container-fluid mt-5 py-3">
        <Link
          to={`/dashboard/pending-task/${id}`}
          className="btn btn-outline-primary btn-sm mb-3 "
        >
          <i className="fas fa-arrow-left"></i> Back to Task Brief
        </Link>
        <div className="row">
          <div className="col-md-5 col-sm-12">
            <div className="card mb-3 tasks" style={{ maxWidth: '23rem' }}>
              <div className="card-header font-weight-bold">Task id {id}</div>
              <div className="card-body px-5">
                <p className="card-text">
                  {tasks.singleTask ? tasks.singleTask.title : <Spin />}
                </p>
              </div>
            </div>
          </div>
          <div className="col-md-7 col-sm-12 submitTask">
            <div className="card">
              <h5 className="submit-card-header"> Submit Task</h5>
              <div className="card-body">
                <Formik
                  initialValues={{ url: '', comments: '' }}
                  validationSchema={Yup.object({
                    url: Yup.string()
                      .url('Enter a valid URL')
                      .required('Enter the URL you wish to submit'),
                    comments: Yup.string().min(15),
                  })}
                  onSubmit={(values, { setSubmitting }) => {
                    const { url, comments } = values;
                    dispatch(submitTaskAction(id, url, comments));
                    setSubmitted(true);
                  }}
                >
                  {({ errors, touched, isSubmmiting }) => (
                    <Form>
                      <div className="form-group mt-5">
                        <label for="FormControlInput font-weight-bold">
                          Url
                        </label>
                        <Field
                          name="url"
                          className={`urlInput form-control ${
                            touched.url && errors.url
                              ? errorClassNames
                              : validClassNames
                          }`}
                          id="FormControlInput"
                          placeholder="Provide the link to your task"
                          type="url"
                        />
                        <div className="d-block text-monospace text-danger small-text">
                          <ErrorMessage name="url" className="d-block" />
                        </div>
                      </div>
                      {/* <a href="/">Submission Guidelines</a> */}

                      <div className="form-group mt-5">
                        <label for="FormControlTextarea font-weight-bold">
                          Comments
                        </label>
                        <Field
                          className={`form-control ${
                            touched.comments && errors.comments
                              ? errorClassNames
                              : validClassNames
                          } `}
                          id="FormControlTextarea"
                          placeholder="Include any challenges encounter"
                          rows="5"
                          as="textarea"
                          name="comments"
                        />
                        <div className="d-block text-monospace text-danger small-text">
                          <ErrorMessage name="comments" className="d-block" />
                        </div>
                      </div>
                      <p className="text-center">
                        {!loading ? (
                          <input
                            value="SUBMIT TASK"
                            type="submit"
                            className="btn btn-lg btn-primary w-75 text-center mt-5 mb-5"
                          />
                        ) : (
                          <span>
                            <Spin /> Submitting ....
                          </span>
                        )}
                      </p>
                    </Form>
                  )}
                </Formik>
              </div>
            </div>
          </div>
        </div>
      </div>
    </SubmitTaskStyled>
  );
}
Example #19
Source File: ForgotPassword.js    From codeclannigeria-frontend with MIT License 4 votes vote down vote up
function ForgotPassword({ history }) {
  const dispatch = useDispatch();
  const authState = useSelector(state => state.auth);
  const { loading, error, errResponse, token } = authState;

  const errorClassNames = 'border input border-danger';
  const validClassNames = 'border input border-green';
  useEffect(() => {
    dispatch({ type: 'AUTH_RESET' });
  }, [dispatch]);

  const openNotification = () => {
    notification.success({
      message: 'Request Successful',
      description: 'Kindly check your email for further instructions',
    });
  };

  useEffect(() => {
    if (token) {
      openNotification();
      history.push('/email-verification-sent/');
    }
  }, [token, history, dispatch]);
  useEffect(() => {
    if (error) {
      message.error(errResponse);
    }
  }, [error, errResponse]);

  return (
    <React.Fragment>
      <Navbar />
      <Formik
        initialValues={{ email: '' }}
        validationSchema={Yup.object({
          email: Yup.string()
            .email('Invalid email address')
            .required('Enter your email address'),
        })}
        onSubmit={(values, { setSubmitting }) => {
          dispatch(fogetPasswordRequestAction(values));
        }}
      >
        {({ 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">Forgot Password?</h1>
                        <p className="text-center mt-4">
                          Enter your email and we’d send you a link to reset
                          your password{' '}
                        </p>
                      </div>

                      <div className="input-group mb-4">
                        <div className="input-group-prepend">
                          <span className="input-group-text">
                            <i className="fas fa-envelope"></i>
                          </span>
                        </div>
                        <Field
                          type="email"
                          className={`form-control ${
                            touched.email && errors.email
                              ? errorClassNames
                              : validClassNames
                          }`}
                          id="forget-Email"
                          name="email"
                          aria-label="forget-Email"
                          aria-describedby="forget-Email"
                        />
                      </div>
                      <div className="d-block text-monospace text-danger small-text">
                        <ErrorMessage name="email" 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>
  );
}
Example #20
Source File: Login.js    From codeclannigeria-frontend with MIT License 4 votes vote down vote up
function LoginForm({ authLogin, loading, error, errResponse, token, history }) {
  const dispatch = useDispatch();
  const passwordRef = useRef();
  useEffect(() => {
    dispatch({ type: 'AUTH_RESET' });
  }, [dispatch]);

  const [passwordDisplay, setpasswordDisplay] = useState(null);

  const togglePasswordToText = ref => {
    setpasswordDisplay(!passwordDisplay);

    if (ref.current.firstChild.type === 'password') {
      ref.current.firstChild.type = 'text';
      // setpasswordDisplay(false);
    } else {
      ref.current.firstChild.type = 'password';
      // setpasswordDisplay(true);
    }
  };

  useEffect(() => {
    const role = checkAuth();
    if (role === 'MENTEE' || role === 'ADMIN') {
      history.push('/dashboard');
    } else if (role === 'MENTOR') {
      history.push('/dashboard/mentor/mentees');
    }
  }, [history]);

  useEffect(() => {
    if (token) {
      const role = checkAuth();
      if (role === 'MENTEE' || role === 'ADMIN') {
        history.push('/dashboard');
      } else if (role === 'MENTOR') {
        history.push('/dashboard/mentor/mentees');
      }
      history.push('/dashboard');
    }
  }, [token, history, dispatch]);

  useEffect(() => {
    if (error) {
      message.error(errResponse);
    }
  }, [error, errResponse]);

  const errorClassNames = 'border input border-danger';
  const validClassNames = 'border input border-green';

  return (
    <Formik
      initialValues={{ email: '', password: '' }}
      validationSchema={Yup.object({
        email: Yup.string()
          .email('Invalid email address')
          .required('Enter your email address'),
        password: Yup.string().required('Enter your password'),
      })}
      onSubmit={(values, { setSubmitting }) => {
        // setSubmitting(true);
        authLogin(values);
        // setSubmitting(false);
      }}
    >
      {({ errors, touched, isSubmitting }) => (
        <LoginStyled>
          <div>
            <div className="main">
              <div className="left">
                <div className="logo">
                  <div>
                    <Link to="/" className="image-link">
                      <img
                        src={codeClanLogo}
                        className="img-fluid"
                        alt="Code clan"
                      />
                    </Link>
                  </div>
                </div>
                <div className="titles"> Login to your account </div>
                <Form>
                  <label htmlFor="email">E-mail</label>{' '}
                  <div className="block">
                    <Field
                      id="email"
                      type="email"
                      name="email"
                      className={
                        touched.email && errors.email
                          ? errorClassNames
                          : validClassNames
                      }
                    />
                    <span>
                      <i className="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="password">Password</label>
                  <div className="block" ref={passwordRef}>
                    <Field
                      id="password"
                      name="password"
                      className={
                        touched.password && errors.password
                          ? errorClassNames
                          : validClassNames
                      }
                      type="password"
                    />
                    <span onClick={() => togglePasswordToText(passwordRef)}>
                      {passwordDisplay ? (
                        <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="password" className="d-block" />
                  </div>
                  <div className="form-con">
                    {/* <div className="checkbox-container">
                      <input
                        type="checkbox"
                        className="regular-checkbox"
                        name="checked"
                      />
                      <span> Remember me </span>
                    </div> */}
                    <Link to="/forgot-password">Forgot password ?</Link>
                  </div>
                  <button
                    disabled={loading}
                    className={loading ? 'btn btn-light w-100' : 'submit'}
                    type="submit"
                  >
                    {!loading ? (
                      'login'
                    ) : (
                      <span className="text-small">
                        <Spinner animation="border" variant="primary" />
                      </span>
                    )}
                  </button>
                  <div className="centralize" style={{ lineHeight: '2em' }}>
                    <p>
                      Don't have an account? <Link to="/register">Sign up</Link>
                    </p>
                  </div>
                </Form>
              </div>
              <div className="right">
                <img
                  alt="Login animation"
                  src={loginAmico}
                  style={{ height: '50%' }}
                />
                <p className="small">CODECLAN NIGERIA</p>
                <p className="normal">
                  Join us and take your programming career to the next level
                </p>
              </div>
            </div>
          </div>
        </LoginStyled>
      )}
    </Formik>
  );
}
Example #21
Source File: ResetPassword.js    From codeclannigeria-frontend with MIT License 4 votes vote down vote up
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>
  );
}
Example #22
Source File: Signup.js    From codeclannigeria-frontend with MIT License 4 votes vote down vote up
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 #23
Source File: AddEdit.jsx    From react-formik-master-details-crud-example with MIT License 4 votes vote down vote up
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 #24
Source File: Register.jsx    From react-signup-verification-boilerplate with MIT License 4 votes vote down vote up
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 #25
Source File: ResetPassword.jsx    From react-signup-verification-boilerplate with MIT License 4 votes vote down vote up
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: AddEdit.jsx    From react-signup-verification-boilerplate with MIT License 4 votes vote down vote up
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 #27
Source File: Update.jsx    From react-signup-verification-boilerplate with MIT License 4 votes vote down vote up
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 #28
Source File: ProductAddEdit.js    From react-sample-projects with MIT License 4 votes vote down vote up
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 #29
Source File: index.js    From realworld with MIT License 4 votes vote down vote up
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>
  );
}