Home > Net >  Form Input Validation ReactJS
Form Input Validation ReactJS

Time:10-19

I have created a form to schedule audits for clients. I need to validate the fields. For clientNo field, the length of the input can be unlimited but the 3rd character from the end must be "-". For example 123456-01 or 1234567-02. If the input requirements is not met, there has to be a feedback saying "Incorrect input". All the fields has to be filled up and there cannot be any null values.

scheduleAuditForm.js

import { FormControl, FormControlLabel, Grid, makeStyles, RadioGroup,Radio, TextField} from "@material-ui/core";
import React, {useState, useEffect} from "react";
import { FormLabel } from "react-bootstrap";
import {useForm,Form} from "../components/useForm";
import Controls from "../components/controls/Controls";
import * as auditService from "../services/auditService"
    
const statusItems = [
    {id:'Confirmed', title:'Confirmed'},
    {id:'Not Initiated', title:'Not Initiated'},
    {id:'Confirmed - DD', title:'Confirmed - DD'},
    {id:'Confirmed - After DD', title:'Confirmed - DD'}

]
const keyAccountItems = [
    {id:'Yes', title:'Yes'},
    {id:'No', title:'No'}

]
const initialFValues = {
    id :0,
    clientNo:'',
    companyName:'',
    planner:'',
    status:'Confirmed',
    leadAuditor:'',
    startDate:new Date(),
    endDate:new Date(),
    cost:'',
    auditStandard:'',
    keyAccount:'Yes',
    auditType:'',
    confirmedMD:'',
    accreditation:'',
    eaCode:''

}    
export default function ScheduleAuditForm(){    
    const{
        values,
        setValues,
        handleInputChange,
        handleClick
    }=useForm(initialFValues);
  
    return(
            <Form >
            <Grid container>
                <Grid item xs={4}>
                <Controls.Input
                    name="clientNo"
                    label="clientNo"
                    type={'number'}
                    value={values.clientNo}
                    onChange = {handleInputChange}

                    />
                    <Controls.Input
                        name="companyName"
                        label="Company Name"
                        value={values.companyName}
                        onChange = {handleInputChange}
                        />
                </Grid>
                <Grid item xs={4}>
                <Controls.Select
                    label='Planner'
                    name='planner'
                    value={values.planner}
                    onChange = {handleInputChange}
                    options={auditService.getAuditCollection2()}        
                    />    
                    </Grid>                                                                                                        
                    </Grid>  
                <div style={{marginLeft:'42px',marginBottom:'50px'}}>
                    <Controls.Button
                    type="button"
                    text="Submit" 
                    onClick = {handleClick}
                    />
                    {/* <Controls.Button
                    text="Reset" 
                    color="default"/> */}
                </div>
                </Grid>
            </Form>
    )
}
   

CodePudding user response:

Use state to keep track of error messages. Perform a validation check when the form is submitted or when the user changes the input and then update the error state. If the error state is not empty then render it to the screen.

You can use slice to get the 3rd last character of a string:

const [error, setError] = useState("")

const validationCheck = () => {
  if (values.clientId.slice(-3, -2) === '-') {
    handleClick()
  } else {
    setError('Client ID must end in -XX')
  }
}

return (
  <Form>
    ...
    {error !== "" && (<p>{error}</p>)}
    <Controls.Button
       type="button"
       text="Submit" 
       onClick = {validationCheck}
    />
  </Form>
)

CodePudding user response:

Here is the simple example:

const {useState, useEffect} = React;

const DemoComponent = (props) => {
  
const [value, setValue] = useState("");
const [valid, setValid] = useState();
const handleValueOnChange = (e) => {
  const value = e.target.value;
  const regex = new RegExp("[0-9] -[0-9]{2}$");
  setValid(value ? regex.test(value) : undefined);
  setValue(value);
};

return (
  <div>
    <div>
      <h4>Rule: </h4>
      <p>123456-01 ○</p>
      <p>1234567-1, -01, 12345, ...etc ×</p>
    </div>
    <hr />
    <div>
      <h4>Try here:</h4>
      <input value={value} onChange={handleValueOnChange} />
      {valid === false && <span> Incorrect input ×</span>}
    </div>
  </div>
);
}

ReactDOM.render(
  <DemoComponent />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Click ↑↑↑ Run code snippet to try it.

Hope to help you !

  • Related