Home > Blockchain >  REACT JS - Function Component Validation
REACT JS - Function Component Validation

Time:10-11

I am a beginner in react. I was working on the react function component with crud. Can anyone please tell how can I apply validation on email text and input text when it is invalid or empty, and show alert if the form is not valid and not continue to next page.

> import { FormGroup, InputLabel, FormControl, Button, Input,
> makeStyles, Typography } from "@material-ui/core" 
> import react, {useState } from "react" 
> import { addContact } from "../Service/api";
> import { useHistory } from "react-router-dom"; 
> import * as React from 'react'; 
> import Box from '@mui/material/Box'; 
> import MenuItem from '@mui/material/MenuItem'; 
> import Select from '@mui/material/Select';
> import TextField from '@mui/material/TextField'; 
> import AdapterDateFns from '@mui/lab/AdapterDateFns'; 
> import LocalizationProvider from
> '@mui/lab/LocalizationProvider'; 
> import DatePicker from '@mui/lab/DatePicker'; 
> 
> const useStyle = makeStyles({
>     container: {
>         width: '50%',
>         margin: '5% 0 0 25%',
>         '& > *': {
>             marginTop: 20
>         }
>     }
> 
> })
> 
> 
> const initialValues = {
>     name: '',
>     email: '',
>     phone: '',
>     location: '' } const AddContact = () => {
>     const [contacts, setContact] = useState(initialValues);
> 
>     const { name, email, phone, location } = contacts;
>     const classes = useStyle();
>     const history = useHistory();
> 
>     const onValueChange = (e) => {
>             setContact({ ...contact, [e.target.name]: e.target.value })
>     }
>     const [regdates, setValue] = React.useState(new Date());
> 
>     let regdate= parseInt(regdates.getMonth() 1)   "/"  regdates.getDate()  "/" regdates.getFullYear();
>     
>     const contact = {...contacts,regdate};
>    
> 
> 
>     const addContactDetails = async () => {
>         await addContact(contact);
>         history.push('./AllContact');
>     }
>  
> 
>     
>     return (
>         <FormGroup className={classes.container}>
>             <Typography variant="h4">Add Contact</Typography>
>             <FormControl>
>                 <InputLabel>Full Name *</InputLabel>
>                 <Input onChange={(e) => onValueChange(e)} name='name' value={name} placeholder="Last Name, First Name Middle Initial"
> required />
>             </FormControl>
>             <FormControl>
>                 <InputLabel>Email Address *</InputLabel>
>                 <Input onChange={(e) => onValueChange(e)} name='email' value={email} placeholder="[email protected]" required/>
>             </FormControl>
>             <FormControl>
>                 <InputLabel>Contact Number *</InputLabel>
>                 <Input onChange={(e) => onValueChange(e)} name='phone' value={phone} placeholder="09XXXXXXXXX" type="number" required/>
>             </FormControl>
>             <Box sx={{ minWidth: 120 }}>
>             <InputLabel>Location *</InputLabel>
> 
>                 <FormControl fullWidth>
>                     <Select
>                         required
>                         onChange={(e) => onValueChange(e)}
>                         value={location}
>                         label="location"
>                         name="location"
>                     >
>                         <MenuItem value="">Select Location</MenuItem>
>                         <MenuItem value="Manila">Manila</MenuItem>
>                         <MenuItem value="Cebu">Cebu</MenuItem>
>                     </Select>
>                 </FormControl>
>             </Box>
>             <FormControl>
>                 <LocalizationProvider dateAdapter={AdapterDateFns}>
>                 <DatePicker
>           disableFuture
>           label="Register Date*"
>           views={['year', 'month', 'day']}
>           value={regdates}
>           name='regdate'
>           onChange={(newValue) => {
>             setValue(newValue);
>           }}
>           renderInput={(params) => <TextField {...params} />}
>         />
>     </LocalizationProvider>
>             </FormControl>
>             <Button variant="contained" onClick={() => addContactDetails()} color="primary">Add Contact</Button>
>         </FormGroup>
>     ) }
> 
> export default AddContact

I'm trying to create crud with validation but this is my first time in react-js/react function component and I dont't know how to add validation.

CodePudding user response:

Maybe this stack overflow question right here can help you out. They use the error prop of MUI component to display the error message, but if you need to create a alert notification, you'll probably need to validate de form inside the submit function and by there, create your error notification.

CodePudding user response:

One of the easiest way is to use Formik. For example like this.

         <Formik
            initialValues={{
              email: '',
            }}
            validationSchema={Yup.object().shape({
              email: Yup.string().email('Must be a valid email').max(255).required('Email is required')
            })}
            onSubmit={(values) => {
              console.log(values.email)
            }}
          >
            {({
              errors,
              handleBlur,
              handleChange,
              handleSubmit,
              isSubmitting,
              touched,
              values
            }) => (
              <form onSubmit={handleSubmit}>
                <TextField
                  error={Boolean(touched.email && errors.email)}
                  fullWidth
                  helperText={touched.email && errors.email}
                  label="Email Address"
                  margin="normal"
                  name="email"
                  onBlur={handleBlur}
                  onChange={handleChange}
                  type="email"
                  value={values.email}
                  variant="outlined"
                />             
                <Box sx={{ py: 2 }}>
                  <Button
                    color="primary"
                    // disabled={isSubmitting}
                    fullWidth
                    size="large"
                    type="submit"
                    variant="contained"
                  >
                   submit
                  </Button>
                </Box>
              </form>
            )}
          </Formik>
  • Related