CRUD – Spring Boot + ReactJS + API Rest + MySQL #10 Validation

Spring – Backend

Controller

src/main/java/com/tutofox/demo/controllers/EmployeeController.java

package com.tutofox.tutospring.controllers;
/.../
import javax.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;

@RestController
@RequestMapping("/api/employee")
public class EmployeeController {
	
  /.../
	
	@PostMapping(value="/create")
	public Map<String, Object> create(@Valid @RequestBody Employee data){
		
		HashMap<String, Object> response = new HashMap<String, Object>();
		
		try {
			
			Optional<Employee> validEmail = employeeRepository.findByEmail(data.getEmail());
			
			if(validEmail.isPresent()) { 
				response.put("message", "The email "+data.getEmail()+" is already registered ");
				response.put("success", false);
				return response;
			}
			else { 
				employeeRepository.save(data);
				response.put("message", "Successful save");
				response.put("success", true);
				return response;
			}
			 
			
		} catch (Exception e) {
			// TODO: handle exception
			response.put("message", e.getMessage());
			response.put("success",false);
			return response;
		}
		
	}

	 
}

Repository

src/main/java/com/tutofox/demo/controllers/src/main/java/com/tutofox/tutospring/repository/EmployeeRepository.java.java

package com.tutofox.tutospring.repository;

import java.util.List;
import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;

import com.tutofox.tutospring.models.Employee;

public interface EmployeeRepository extends JpaRepository<Employee, Integer>{

	/.../
  	
	Optional<Employee> findByEmail(String email);
 
 
}

Model

src/main/java/com/tutofox/tutospring/models/Employee.java

package com.tutofox.tutospring.models;

/.../
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import javax.validation.constraints.Digits;
import javax.validation.constraints.Email;
 
 

@Entity 
@Table(name="employee")
public class Employee {
	
   /.../
          
 	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name="id")
	private Integer id;
	
	@NotEmpty(message = "The email field is required")
	@Email(message = "The value '${validatedValue}' must be a valid email address")
	@Column(name = "email")
	private String email; 
	@Pattern(regexp = "^[\\p{L} .'-]+$", message = "The name field may only contain letters")
	@Column(name = "name")
	private String name;
	 
	@Digits(integer = 10,fraction = 0, message = "The phone field must be less than or equual to 10")
	@Column(name = "phone")
	private Long phone;
	
	@NotEmpty(message = "The address field is required")
	@Column(name = "address")
	private String address;
	

}

ReactJS – Frontend

Services Employee

src/main/resources/js/components/services/Employee.js

const baseUrl = "http://localhost:8080/api/employee"
import axios from "axios";
const employee = {};

employee.create = async (state) => {

  const datapost = {
    name: state.fieldName,
    email: state.fieldEmail,
    phone: state.fieldPhone,
    address: state.fieldAddress
  }

  const urlPost = baseUrl+"/create"

  const res = await axios.post(urlPost,datapost)
  .then(response=>{ return response.data; })
  .catch(error=>{ return error.response; })
  
  return res;
}

export default employee

Form

src/main/resources/js/components/employee/Form.js

import React, { Component } from 'react';

import employeeServices from "../services/Employee"

export default class Form extends Component {

	constructor(){
		super();
		this.state = {
			fieldName:"",
			fieldEmail:"",
			fieldAddress:"",
			fieldPhone:"",
			errorField:[]
		}
	}

  render() {
    return (
      <div>
      	<h4>Create employee v2 </h4>
        <div class="row">
          <div class="col-md-6 mb-3">
            <label for="firstName">Name employee</label>
            <input type="text" class="form-control" placeholder="Name"
            	value={this.state.fieldName}
            	onChange={(event)=>this.setState({fieldName:event.target.value})}
            	/>
          </div>
        </div>

				<div class="row">
          <div class="col-md-6 mb-3">
						<label for="email">Email</label>
	          <input type="email" class="form-control" placeholder="[email protected]"
	        	  value={this.state.fieldEmail}
          		  onChange={(event)=>this.setState({fieldEmail:event.target.value})}
	        	  />
          </div>
        </div>

				<div class="row">
          <div class="col-md-6 mb-3">
						<label for="address">Address</label>
	          <input type="text" class="form-control" placeholder="1234 Main St"
							value={this.state.fieldAddress}
							onChange={(event)=>this.setState({fieldAddress:event.target.value})}
						/>
          </div>
        </div>

				<div class="row">
          <div class="col-md-6 mb-3">
						<label for="phone">Phone </label>
	          <input type="text" class="form-control" placeholder="123467890"
							value={this.state.fieldPhone}
							onChange={(event)=>this.setState({fieldPhone:event.target.value})}
						/>
          </div>
        </div>

				<div class="row">
          <div class="col-md-6 mb-3">
						<label for="phone">Phone </label>
	          <input type="text" class="form-control" placeholder="123467890"
							value={this.state.fieldPhone}
							onChange={(event)=>this.setState({fieldPhone:event.target.value})}
						/>
          </div>
        </div>

				{
					this.state.errorField.map((itemerror)=>{
						return(
							<p class="text-danger">*{itemerror}</p>
						)
					})
				}

				<div class="row">
					<div class="col-md-6 mb-3">
		      	<button onClick={()=>this.onClickSave()} class="btn btn-primary btn-block" type="submit">Save</button>
					</div>
				</div>
      </div>
    )
  }

	async onClickSave()
	{
		const res = await employeeServices.create(this.state)
		if (res.success) {
			alert(res.message)
			console.log(res);
			// window.location.replace("/employee/index")
		}
		else if (res.status==400) {
			console.log(res.status);
			const dataError = []
			const error = res.data.errors

			if (error) {
				error.map((itemerror)=>{
					console.log(itemerror.defaultMessage);
					dataError.push(itemerror.defaultMessage)
				})
				this.setState({errorField:dataError})
			}
			else {
				dataError.push(res.data.message)
				this.setState({errorField:dataError})
			}
		}
		else {
			// alert("Error ==>"+JSON.stringify(res))
			console.log(res);
			const dataError = []
			dataError.push(res.message);
			this.setState({errorField:dataError});
		}
	}

}

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *