Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form submit and validation with MaterialUI & ReactJS

I'm moving from AntD to MaterialUI and can't figure out how to easily implement form validation AND form submission without reloading the whole page.

As an example, upon clicking "sign in" the whole page reloads, which isn't a good idea with an SPA app.

I can bypass that by moving the handleFunction from the element to the element's onClick function and removing the type="submit" from the Button so as not to reload the whole page. That works but it removes the validation and it removes the ability for the user to click "Enter" to submit the form.

Any idea how to achieve this? Below is what I have so far which works but without form validation and without being able to click 'enter' to submit the form:

    return (
    <Container component="main" maxWidth="xs">
        <CssBaseline/>
        <div className={classes.paper}>
            <Avatar className={classes.avatar}>
                <LockOutlinedIcon/>
            </Avatar>
            <Typography component="h1" variant="h5">
                Sign in
            </Typography>
            <form className={classes.form}>
                <TextField
                    variant="outlined"
                    margin="normal"
                    required
                    fullWidth
                    id="email"
                    label="Email Address"
                    name="email"
                    autoComplete="email"
                    autoFocus
                    errorMessages={['this field is required', 'email is not valid']}
                    onInput={e => setEmail(e.target.value)}
                />
                <TextField
                    variant="outlined"
                    margin="normal"
                    required
                    fullWidth
                    name="password"
                    label="Password"
                    type="password"
                    id="password"
                    autoComplete="current-password"
                    onInput={e => setPassword(e.target.value)}
                />
                <FormControlLabel
                    control={<Checkbox value="remember" color="primary"/>}
                    label="Remember me"
                />
                <Button
                    fullWidth
                    variant="contained"
                    color="primary"
                    className={classes.submit}
                    onClick={onFinish}
                >
                    Sign In
                </Button>
                <Grid container>
                    <Grid item xs>
                        <Link to={"/forgotpassword1"} variant="body2">
                            Forgot password?
                        </Link>
                    </Grid>
                    <Grid item>
                        <Link to={"/register"} variant="body2">
                            {"Don't have an account? Sign Up"}
                        </Link>
                    </Grid>
                </Grid>
            </form>
        </div>

    </Container>
);
like image 206
Vladimir Avatar asked Mar 14 '26 09:03

Vladimir


2 Answers

You can try it:

...

export default function SignIn() {
  ...
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [emailErrorText, setEmailErrorText] = React.useState("");
  const [passwordErrorText, setPasswordErrorText] = React.useState("");

  const onSubmit = e => {
    e.preventDefault();
    
    if (!email) {
      setEmailErrorText("Please enter email");
    } else {
      setEmailErrorText("");
    }
    if (!password) {
      setPasswordErrorText("Please enter password");
    } else {
      setPasswordErrorText("");
    }
  };

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div className={classes.paper}>
        <Typography component="h1" variant="h5">
          Sign in
        </Typography>
        <form className={classes.form} noValidate>
          <TextField
            variant="outlined"
            margin="normal"
            required
            type="email"
            fullWidth
            id="email"
            label="Email Address"
            name="email"
            autoComplete="email"
            autoFocus
            value={email}
            error={!!emailErrorText}
            helperText={emailErrorText}
            onChange={e => setEmail(e.target.value)}
          />
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            name="password"
            label="Password"
            type="password"
            id="password"
            autoComplete="current-password"
            value={password}
            error={!!passwordErrorText}
            helperText={passwordErrorText}
            onChange={e => setPassword(e.target.value)}
          />
          <FormControlLabel
            control={<Checkbox value="remember" color="primary" />}
            label="Remember me"
          />
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
            onClick={onSubmit}
          >
            Sign In
          </Button>
          <Grid container>
            <Grid item xs>
              <Link href="#" variant="body2">
                Forgot password?
              </Link>
            </Grid>
            <Grid item>
              <Link href="#" variant="body2">
                {"Don't have an account? Sign Up"}
              </Link>
            </Grid>
          </Grid>
        </form>
      </div>
      <Box mt={8}>
        <Copyright />
      </Box>
    </Container>
  );
}

Edit Select with checkboxes and sub headers

like image 183
Michael Avatar answered Mar 16 '26 22:03

Michael


We can achieve this by adding preventDefault while onSubmit.

handleSubmit:

const handleSubmit = e => {
    e.preventDefault();
    console.log("submit");
};

onSubmit:

<form className={classes.form} noValidate onSubmit={handleSubmit}>

Check the updated code in codesandbox

like image 43
Gokulakannan T Avatar answered Mar 16 '26 22:03

Gokulakannan T