import React, {PureComponent} from 'react' import PropTypes from "prop-types"; /** * Components that renders the form to request quote. */ export class OrderForm extends PureComponent { static get propTypes() { return { isProcessing: PropTypes.bool, isProcessingComplete: PropTypes.bool, onClickSubmit: PropTypes.func, }; } constructor(props) { super(props); this.state = { note: '', email: '', error: { note: null, email: null, }, empty: { note: null, email: null, }, }; this.handleEmail = this.handleEmail.bind(this); this.handleNote = this.handleNote.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.resetEmptyError = this.resetEmptyError.bind(this); this.checkValidation = this.checkValidation.bind(this); } checkValidation() { let isValid = true; let validationFields = {...this.state}; const { isEmpty: isEmailEmpty, isError: isEmailError } = this.validateEmail(this.state.email); validationFields = { ...validationFields, error: { ...this.state.error, email: isEmailError, }, empty: { ...this.state.empty, email: isEmailEmpty, } } this.setState(validationFields); isValid = !isEmailEmpty && !isEmailError return isValid; } validateEmail(value) { let isEmpty = null; let isError = null; const { t } = this.props; if (!value || value.trim() === '') { isEmpty = true; } else if (value && !value.match(/^\w+([\+\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/)) { isError = { message: 'Your email is incomplete', }; } return { isEmpty, isError }; } validateNote(value) { let isEmpty = null; if (!value || value.trim() === '') { isEmpty = true; } return { isEmpty }; } resetEmptyError(key) { this.setState({ ...this.state, error: { ...this.state.error, [key]: null, }, empty: { ...this.state.empty, [key]: null, }, }); } handleEmail(e) { const value = e.target.value; const { isEmpty, isError } = this.validateEmail(value); this.setState({ ...this.state, email: value, error: { ...this.state.error, email: isError, }, empty: { ...this.state.empty, email: isEmpty, } }); } handleNote(e) { const value = e.target.value; this.setState({ ...this.state, note: value, }); } handleSubmit(event) { event.preventDefault(); if (this.props.onClickSubmit) { // check validation input fields const isValidated = this.checkValidation(); if (!isValidated) { return false; } this.props.onClickSubmit(this.state.note, this.state.email); } } render() { const { handleEmail, handleNote, resetEmptyError, handleSubmit, } = this; const { onClickShow, } = this.props; const { email, note, error, empty } = this.state; const { isProcessing, isProcessingComplete } = this.props; return (
resetEmptyError('email')} onChange={handleEmail} onBlur={handleEmail} value={email} /> { empty && empty.email ? (
Required
) : null} { error && error.email ? (
Your email is incomplete
) : null}