Home > database >  How to check validation field required in Form when onClick button
How to check validation field required in Form when onClick button

Time:10-21

I have TextField Here is my code.

 <Textfield
      required
      label="Required Field"
      requiredMessage="This field is required."
      errorTarget="under"
      name="field"
      onChange={(e) => handleChaneValue(e)}
      />
  <Button 
      ui="confirm" 
      text="BTN submit" 
      handler={handleClick} 
      style={{border: '1px solid black'}}
      />

I want when click Button if field not value show error messeger. enter image description here

CodePudding user response:

You should:

  • When textfField change, update state of your component (that is the value of textfield) ==> Two ways binding will be necessary (Data binding in React)

  • Then, you create your error message div (where you want and with the style you need), and you add style display:none

  • Then, on click (button), you check the state value of textField. If it's empty, you change style of the error message div ==> display:block

CodePudding user response:

Please refer to the following code.

Note: The code is only looking for a single TextField. I have used material-ui TextField and Button component(I am not sure which one you're using). However, the logic should remain the same.

import React, { useState } from 'react';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';

function App() {
  const [field, setField] = useState('');
  const [error, setError] = useState(false);
  const handleClick = () => {
    if (!field) {
      setError(true);
      return null;
    }
  };
  const handleChangeValue = (e) => {
    setField(e.target.value);
  };
  return (
    <div>
      <TextField
        required
        label="Required Field"
        value={field}
        error={!!error}
        name="field"
        onChange={(e) => handleChangeValue(e)}
        helperText={error ? 'this is required' : ''}
      />
      <Button onClick={handleClick} style={{ border: '1px solid black' }}>
        Submit
      </Button>
    </div>
  );
}
export default App;
  • Related