Search code examples
javascriptreactjstypescriptreact-fullstack

how to use separate validation form in react js


I am new to ReactJS.

I want to separate the validation code from this file and move it to a new file that handles validation.

When I am trying to send the props from the render method, it is showing the validation three or four times. I know this is not the right way to do this.

import React from 'react';
import { Button, Form, FormGroup, Label, Input } from 'reactstrap';
import { NotificationManager } from 'react-notifications';
import {AddService} from '../../api/service'
import { CSelect } from '@coreui/react';
import Validation from '../validation/service'

class AddEditForm extends React.Component {

    state = {
        id: '',
        name: '',
        description: '',
        duration:'',
        price: '',
        validation : false,
    }

    onChange = e => {
        this.setState({ [e.target.name]: e.target.value })
    }

    submitFormAdd = async(e) => {
        e.preventDefault ()
        await this.Validation()
        if (this.state.validation == true) {
        //API
        }
    }

    submitFormEdit = async(e) => {
        e.preventDefault ()
        await this.Validation()
        if (this.state.validation == true) {
            //API
        }
    }

// VALIDATION FILE

    Validation = (e) => {

        let isnum = /^\d+$/.test(this.state.price);
        if (!this.state.name) {
            NotificationManager.error('Please Enter Service Name', 'Info', 2000)
            return false;
        }
        if (!this.state.description) {
            NotificationManager.error('Please Enter Description', 'Info', 2000)
            return false;
        }
        if (!this.state.price) {
            NotificationManager.error('Please Phone price', 'Error', 2000)
            return false
        }
        if (!this.state.duration) {
            NotificationManager.error('Please Service Duration', 'Error', 2000)
            return false
        }
        if (isnum !== true) {
            NotificationManager.error('Please Enter Price in Number', 'Error', 2000)
            return false
        }
        else {
           this.setState({validation : true})
        }
    }

    componentDidMount() {
        if (this.props.item) {
            const { id, name, description, price, duration } = this.props.item
            this.setState({ id, name, description, price, duration })
        }
    }

    render() {
        return (
            <Form onSubmit={this.props.item ? this.submitFormEdit : this.submitFormAdd}>
                <FormGroup>
                    <Label for="name">Name</Label>
                    <Input type="text" name="name" id="name" onChange={this.onChange} value={this.state.name === null ? '' : this.state.name} />
                </FormGroup>
                <FormGroup>
                    <Label for="description">Description</Label>
                    <Input type="text" name="description" id="description" onChange={this.onChange} value={this.state.description === null ? '' : this.state.description} />
                </FormGroup>
                <FormGroup>
                    <Label for="price">Price</Label>
                    <Input type="price" name="price" id="price" onChange={this.onChange} value={this.state.price === null ? '' : this.state.price} />
                </FormGroup>
                <FormGroup>
                    <Label for="duration">Duration</Label>
                    <CSelect custom size="lg" name="selectLg" id="selectLg" value={this.state.duration} onChange={(e) => this.setState({duration : e.target.value})}>
                      <option value="">Select Duration</option>
                      <option value="3 Months">3 Months</option>
                      <option value="6 Months">6 Months</option>
                      <option value="1 year">1 year</option>
                      <option value="2 year">2 year</option>
                      <option value="4 year">4 year</option>
                    </CSelect>
                </FormGroup>
                <Button>Submit</Button>
            </Form>
        );
    }
}

export default AddEditForm

I want form validation in separate file and validate it through prop:

Validation = (e) => {

        let isnum = /^\d+$/.test(this.state.price);
        if (!this.state.name) {
            NotificationManager.error('Please Enter Service Name', 'Info', 2000)
            return false;
        }
        if (!this.state.description) {
            NotificationManager.error('Please Enter Description', 'Info', 2000)
            return false;
        }
        if (!this.state.price) {
            NotificationManager.error('Please Phone price', 'Error', 2000)
            return false
        }
        if (!this.state.duration) {
            NotificationManager.error('Please Service Duration', 'Error', 2000)
            return false
        }
        if (isnum !== true) {
            NotificationManager.error('Please Enter Price in Number', 'Error', 2000)
            return false
        }
        else {
           this.setState({validation : true})
        }
    }

Solution

  • All you need to do is create the file and create a function in that file. This question has an answer that explains it

    How to create helper file full of functions in react native?

    you need to create the file validation.js

    then

    export function validation(e){
    //your code
    
    }
    

    then import it in the file you currently have like this

    import {validation} from './utils/validation'