0

I work on a React project. I wrote HTML codes for create form. There is validation in HTML scripts. I wrote validations but validations doesn't work. The code is below. For example I want the relevant field to be red when the name is not entered or I want it to give a warning message when the name does not comply with the text rules. I must do it without any library. How can I fix it ?

import React, { Component } from 'react'
import EmployeeService from '../services/EmployeeService';

class CreateEmployeeComponent extends Component {
    constructor(props) {
        super(props)

        this.state = {

            id: this.props.match.params.id,
            firstName: '',
            lastName: '',
            emailId: ''
        }
    }

    componentDidMount(){

        if(this.state.id === '_add'){
            return
        }else{
            EmployeeService.getEmployeeById(this.state.id).then( (res) =>{
                let employee = res.data;
                this.setState({firstName: employee.firstName,
                    lastName: employee.lastName,
                    emailId : employee.emailId
                });
            });
        }        
    }
    saveOrUpdateEmployee = (e) => {
        e.preventDefault();
        let employee = {firstName: this.state.firstName, lastName: this.state.lastName, emailId: this.state.emailId};
        console.log('employee => ' + JSON.stringify(employee));

        // step 5
        if(this.state.id === '_add'){
            EmployeeService.createEmployee(employee).then(res =>{
                this.props.history.push('/employees');
            });
        }else{
            EmployeeService.updateEmployee(employee, this.state.id).then( res => {
                this.props.history.push('/employees');
            });
        }
    }
    
    changeFirstNameHandler= (event) => {
        this.setState({firstName: event.target.value});
    }

    changeLastNameHandler= (event) => {
        this.setState({lastName: event.target.value});
    }

    changeEmailHandler= (event) => {
        this.setState({emailId: event.target.value});
    }

    cancel(){
        this.props.history.push('/employees');
    }

    getTitle(){
        if(this.state.id === '_add'){
            return <h3 className="text-center">Add Employee</h3>
        }else{
            return <h3 className="text-center">Update Employee</h3>
        }
    }

    onSubmit = e => {
        e.preventDefault();
    }

    render() {
        return (
            <div>
                <br></br>
                   <div className = "container">
                        <div className = "row">
                            <div className = "card col-md-6 offset-md-3 offset-md-3">
                                {
                                    this.getTitle()
                                }
                                <div className = "card-body">
                                <form onSubmit={this.onSubmit} noValidate>
                                        <div className = "form-group">
                                        <label for="validationCustom01" class="form-label">First name</label>
                                            <input type='text' maxLength={20} pattern='[A-Za-z]' placeholder="First Name" name="firstName" className="form-control" 
                                                value={this.state.firstName} onChange={this.changeFirstNameHandler} required/>
                                        </div>
                                        <div className = "form-group">
                                            <label> Last Name: </label>
                                            <input type='text' maxLength={20} pattern='[A-Za-z]'class="form-control" placeholder="Last Name" name="lastName" className="form-control" 
                                                value={this.state.lastName} onChange={this.changeLastNameHandler} required/>
                                        </div>
                                        <div className = "form-group">
                                            <label> Email Id: </label>
                                            <input type='email' maxLength={35} pattern='[A-Za-z]' placeholder="Email Address" name="emailId" className="form-control" 
                                                value={this.state.emailId} onChange={this.changeEmailHandler} required/> 
                                        </div>
                                        <button type="submit" className="btn btn-success" onClick={this.saveOrUpdateEmployee}>Save</button>
                                        <button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button>
                                    </form>
                                </div>
                            </div>
                        </div>

                   </div>
            </div>
        )
    }   
}

export default CreateEmployeeComponent

1 Answers1

0

Remove noValidate from your <form> element.

Additionally, I've personally found that Formik and Yup can be a helpful library.
(Sorry I missed that "no libraries" wasa constraint)

Edit:

I was a muppet and forgot to change the pattern You can do one of 2 things:

  1. Remove maxLength and change the pattern to pattern="[A-Za-z]{1,20}"
    Where 20 will be the new max-length (so 20 or 35, depending on the field)

  2. Only change the pattern to be pattern="[A-Za-z]+"
    The + is needed to ensure 1 or more of the [A-Za-z] regex is done. https://regexr.com/

Also don't forget to remove noValidate from your <form> element.

This answer may also prove helpful in setting custom validity status messages and callbacks.

Harrison
  • 1,654
  • 6
  • 11
  • 19
  • It doesnt't work. I must do it without any library. @HarrisonRaybould –  Oct 20 '22 at 08:08
  • Unfortunately it doesn't work. I tried the link what you send but I couldn't work it. Can you write sample code scripts? @HarrisonRaybould –  Oct 20 '22 at 09:03
  • Which bit isn't working? Have you changed the `novalidate`? It should go from `
    ` to `
    ` You may also have to put the `htmlFor` key in your `
    – Harrison Oct 20 '22 at 09:12
  • I remove noValidate on form element but it doesn't work and I edited pattern regex but it doesn't work too. @HarrisonRaybould –  Oct 20 '22 at 09:17
  • Please show your changes, maybe as an Edit to your original question – Harrison Oct 20 '22 at 09:30