Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

Using these validations: [code] Rewrite these inputs so some of them are validated.…

  1. User

    Using these validations:

    
    // globalny kill switch do debugowania walidacji (zwraca zawsze sukces)
    const debugMode = false;
    
    export const requiredField = (msg) => {
        return {
            required: true,
            message: msg,
            validator: (_, value) => {
                if (debugMode) return Promise.resolve();
                if (value) return Promise.resolve();
                return Promise.reject(new Error(msg));
            },
        };
    };
    
    export const validatePassword = {
        validator: (_, value) => {
            if (debugMode) return Promise.resolve();
            if (value && value.length >= 6) {
                return Promise.resolve();
            }
            return Promise.reject(new Error('Password must be at least 6 characters'));
        },
    };
    
    export const validateConfirmPasssword = (getFieldValue) => ({
        validator(_, value) {
            if (debugMode) return Promise.resolve();
            if (!value || getFieldValue('newPassword') === value) {
                return Promise.resolve();
            }
            return Promise.reject(new Error('The two passwords that you entered do not match!'));
        },
    });
    
    
    export const polishPhoneValidation = {
        pattern: /^[0-9]{9}$/,
        message: 'Enter a valid Polish phone number (9 digits)',
        validator: (_, value) => {
            if (debugMode) return Promise.resolve();
            if (value && polishPhoneValidation.pattern.test(value)) {
                return Promise.resolve();
            }
            return Promise.reject(new Error(polishPhoneValidation.message));
        },
    };
    
    export const swedishPhoneValidation = {
        pattern: /^[0-9]{9,10}$/,
        message: 'Enter a valid Swedish phone number (9-10 digits)',
        validator: (_, value) => {
            if (debugMode) return Promise.resolve();
            if (value && swedishPhoneValidation.pattern.test(value)) {
                return Promise.resolve();
            }
            return Promise.reject(new Error(swedishPhoneValidation.message));
        },
    };
    
    export const universalFieldValidation = (fieldName) => ({
        pattern: /^[A-Za-zÀ-ÖØ-öø-ÿ\s'-]+$/,
        max: 50,
        message: `Enter a valid ${fieldName} (max 50 characters)`,
        validator: (_, value) => {
            if (debugMode) return Promise.resolve();
            if (value && universalFieldValidation(fieldName).pattern.test(value) && value.length <= universalFieldValidation(fieldName).max) {
                return Promise.resolve();
            }
            return Promise.reject(new Error(universalFieldValidation(fieldName).message));
        },
    });
    
    export const validatePESEL = {
        validator: (_, value) => {
            if (debugMode) return Promise.resolve();
            if (!value) return Promise.resolve();
    
            const peselPattern = /^[0-9]{11}$/;
            if (!peselPattern.test(value)) {
                return Promise.reject(new Error('PESEL must consist of exactly 11 digits.'));
            }
    
            // walidatcja daty urodzenia w PESEL
            const year = parseInt(value.substring(0, 2), 10);
            const month = parseInt(value.substring(2, 4), 10) % 20;
            const day = parseInt(value.substring(4, 6), 10);
    
            const currentYear = new Date().getFullYear() % 100;
            const century = month > 12 ? 2000 : (year <= currentYear ? 1900 : 1800);
            const fullYear = century + year;
    
            const birthDate = new Date(fullYear, month - 1, day);
            if (birthDate.getFullYear() !== fullYear || birthDate.getMonth() + 1 !== month || birthDate.getDate() !== day) {
                return Promise.reject(new Error('Invalid PESEL date.'));
            }
    
            // checksum PESEL'u
            const weights = [1, 3, 7, 9, 1, 3, 7, 9, 1, 3];
            const sum = value.split('').reduce((acc, digit, idx) => {
                if (idx < 10) {
                    acc += parseInt(digit, 10) * weights[idx];
                }
                return acc;
            }, 0);
            const checksum = (10 - (sum % 10)) % 10;
    
            if (checksum !== parseInt(value.charAt(10), 10)) {
                return Promise.reject(new Error('Invalid PESEL checksum.'));
            }
    
            return Promise.resolve();
        },
        message: 'Invalid PESEL number.',
    };
    
    export const validateNIP = {
        validator: (_, value) => {
            if (debugMode) return Promise.resolve();
            if (!value) return Promise.resolve();
    
            const nipPattern = /^[0-9]{10}$/;
            if (!nipPattern.test(value)) {
                return Promise.reject(new Error('NIP must consist of exactly 10 digits.'));
            }
    
            // checksum NIP'u
            const weights = [6, 5, 7, 2, 3, 4, 5, 6, 7];
            const sum = value.split('').reduce((acc, digit, idx) => {
                if (idx < 9) {
                    acc += parseInt(digit, 10) * weights[idx];
                }
                return acc;
            }, 0);
            const checksum = sum % 11;
    
            if (checksum !== parseInt(value.charAt(9), 10)) {
                return Promise.reject(new Error('Invalid NIP checksum.'));
            }
    
            return Promise.resolve();
        },
        message: 'Invalid NIP number.',
    };
    
    export const validateEmail = {
        validator: (_, value) => {
            if (debugMode) return Promise.resolve();
            if (!value) return Promise.resolve();
    
            const emailPattern = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
    
            if (!emailPattern.test(value)) {
                return Promise.reject(new Error('Invalid email format.'));
            }
    
            return Promise.resolve();
        },
        message: 'Please enter a valid email address.',
    };
    
    

    Rewrite these inputs so some of them are validated. Don't break frontend composition of forms

    import React, { useEffect, useState } from "react";
    import { Link, useParams } from "react-router-dom";
    import AmberBox from "../../Components/AmberBox";
    import { Input, Select, Button, AutoComplete } from "antd";
    import Axios from "axios";
    
    const { Option } = Select;
    
    export default function EdytujProjektPage() {
        const [availableGroups, setAvailableGroups] = useState([]);
        const [availableProjects, setAvailableProjects] = useState([]);
        const { id } = useParams();
    
        const [form, setForm] = useState({
            firma: '1',
            zleceniodawca: '',
            nazwa: '',
            kodProjektu: '',
            ulica: '',
            miejscowosc: '',
            kodPocztowy: '',
            kraj: ''
        });
    
        const fetchGroups = () => {
            Axios.get("http://localhost:5000/api/grupy", { withCredentials: true })
                .then((response) => {
                    const transformedData = response.data.grupy.map(grupy => ({
                        name: grupy.Zleceniodawca,
                        value: grupy.id
                    }));
                    setAvailableGroups(transformedData);
                })
                .catch((error) => {
                    console.error(error);
                });
        };
    
        const fetchProjects = () => {
            Axios.get("http://localhost:5000/api/czas/projekty", { withCredentials: true })
                .then((response) => {
                    const transformedDataProjects = response.data.projekty.map(projekty => ({
                        name: projekty.NazwaKod_Projektu,
                        value: projekty.idProjekty
                    }));
                    setAvailableProjects(transformedDataProjects);
                })
                .catch((error) => {
                    console.error(error);
                });
        };
    
        const fetchProjectData = (projectId) => {
            Axios.get(`http://localhost:5000/api/czas/projekty/${projectId}`, { withCredentials: true })
                .then((response) => {
                    if (response.data && Array.isArray(response.data) && response.data.length > 0) {
                        const project = response.data[0];
                        setForm({
                            firma: project.Firma_idFirma || '1',
                            zleceniodawca: project.Grupa_urlopowa_idGrupa_urlopowa || '',
                            nazwa: project.NazwaKod_Projektu || '',
                            kodProjektu: project.NazwaKod_Projektu || '',
                            ulica: project.Ulica || '',
                            miejscowosc: project.Miejscowosc || '',
                            kodPocztowy: project.Kod_pocztowy || '',
                            kraj: project.Kraj || ''
                        });
                        console.log(project);
                    }
                })
                .catch((error) => {
                    console.error('Error fetching project:', error);
                });
        };
    
        useEffect(() => {
            fetchGroups();
            fetchProjects();
            fetchProjectData(id);
        }, [id]);
    
        const handleSave = () => {
            Axios.put(`http://localhost:5000/api/czas/edytujProjekt/${id}`, form, { 
                withCredentials: true 
            })
            .then(res => {
                window.location.href = "/home/projekty";
            })
            .catch(err => {
                console.error("Error updating project:", err.response ? err.response.data : err.message);
            });
        };
    
        const handleChange = (value, field) => {
            setForm(prevState => ({
                ...prevState,
                [field]: value
            }));
        };
    
        return (
            <div>
                <div className="w-auto h-auto bg-blue-700 outline outline-1 outline-black flex flex-row items-center space-x-4 m-2 p-3 text-white">
                    <p>Edytuj projekt</p>
                </div>
                <AmberBox>
                    <div className="flex flex-col items-center space-y-8 p-4 w-full">
    
                        <div className="w-full md:w-6/12 lg:w-4/12">
                            <label htmlFor="firma">Firma</label>
                            <Select
                                onChange={(value) => handleChange(value, 'firma')}
                                className="w-full"
                                value={form.firma}
                                showSearch
                                allowClear
                            >
                                <Option key={1} value={1}>
                                    PC Husbyggen
                                </Option>
                            </Select>
                        </div>
    
                        <div className="w-full md:w-6/12 lg:w-4/12">
                            <label htmlFor="zleceniodawca">Zleceniodawca</label>
                            <Select
                                onChange={(value) => handleChange(value, 'zleceniodawca')}
                                className="w-full"
                                value={form.zleceniodawca}
                                showSearch
                                allowClear
                            >
                                {availableGroups.map((group) => (
                                    <Option key={group.value} value={group.value}>
                                        {group.name}
                                    </Option>
                                ))}
                            </Select>
                        </div>
    
                        <div className="w-full md:w-6/12 lg:w-4/12">
                            <label htmlFor="nazwa">Nazwa/Kod Projektu</label>
                            <AutoComplete
                                onChange={(value) => handleChange(value, 'nazwa')}
                                className="w-full"
                                value={form.nazwa}
                                options={availableProjects.map(project => ({
                                    value: project.value,
                                    label: project.name
                                }))}
                                placeholder="Wybierz projekt"
                                filterOption={(inputValue, option) =>
                                    option.label.toLowerCase().includes(inputValue.toLowerCase())
                                }
                                allowClear
                            />
                        </div>
    
                        <div className="w-full md:w-6/12 lg:w-4/12">
                            <label htmlFor="ulica">Ulica</label>
                            <Input onChange={(e) => handleChange(e.target.value, 'ulica')} value={form.ulica} />
                        </div>
    
                        <div className="w-full md:w-6/12 lg:w-4/12">
                            <label htmlFor="miejscowosc">Miejscowość</label>
                            <Input onChange={(e) => handleChange(e.target.value, 'miejscowosc')} value={form.miejscowosc} />
                        </div>
    
                        <div className="w-full md:w-6/12 lg:w-4/12">
                            <label htmlFor="kodPocztowy">Kod pocztowy</label>
                            <Input onChange={(e) => handleChange(e.target.value, 'kodPocztowy')} value={form.kodPocztowy} />
                        </div>
    
                        <div className="w-full md:w-6/12 lg:w-4/12">
                            <label htmlFor="kraj">Kraj</label>
                            <Input onChange={(e) => handleChange(e.target.value, 'kraj')} value={form.kraj} />
                        </div>
    
                        <div className="flex space-x-4 mt-8">
                            <Button type="primary" onClick={handleSave}>Zapisz</Button>
                            <Link to="/home/projekty">
                                <Button>Anuluj</Button>
                            </Link>
                        </div>
                    </div>
                </AmberBox>
            </div>
        );
    }
    
  2. Assistant

    To validate some of the inputs in your EdytujProjektPage component without breaking the frontend composition of your forms, you can leverage the Ant Design Form component along with your custom validation functions. Here's how you can modify your code:

    1. Import the Form component from Ant Design:

      import { Input, Select, Button, AutoComplete, Form } from "antd";
      
    2. Initialize the form instance using Form.useForm():

      const [form] = Form.useForm();
      
    3. Remove the custom useState hook for form data: Since we'll be using Ant Design's form management, you can remove the useState for form:

      // Remove this:
      // const [form, setForm] = useState({ ... });
      
    4. Set form values using form.setFieldsValue(): In your fetchProjectData function, update the form fields with the fetched data:

      form.setFieldsValue({
          firma: project.Firma_idFirma || '1',
          zleceniodawca: project.Grupa_urlopowa_idGrupa_urlopowa || '',
          nazwa: project.NazwaKod_Projektu || '',
          kodProjektu: project.NazwaKod_Projektu || '',
          ulica: project.Ulica || '',
          miejscowosc: project.Miejscowosc || '',
          kodPocztowy: project.Kod_pocztowy || '',
          kraj: project.Kraj || ''
      });
      
    5. Wrap your inputs within the Form component:

      <Form form={form} onFinish={handleSave}>
          {/* Form items and buttons */}
      </Form>
      
    6. Use Form.Item to wrap each input and apply validation rules: For example, here's how you can modify the "Firma" input:

      <Form.Item
          label="Firma"
          name="firma"
          rules={[requiredField('Firma is required')]}
      >
          <Select className="w-full" showSearch allowClear>
              <Option key={1} value={1}>
                  PC Husbyggen
              </Option>
          </Select>
      </Form.Item>
      
    7. Adjust the handleSave function to receive form values:

      const handleSave = (values) => {
          Axios.put(`http://localhost:5000/api/czas/edytujProjekt/${id}`, values, { 
              withCredentials: true 
          })
          .then(res => {
              window.location.href = "/home/projekty";
          })
          .catch(err => {
              console.error("Error updating project:", err.response ? err.response.data : err.message);
          });
      };
      
    8. Update the remaining inputs with appropriate validation: Apply the necessary validation rules to other inputs using your custom validation functions. Here's the complete modified component:

      import React, { useEffect, useState } from "react";
      import { Link, useParams } from "react-router-dom";
      import AmberBox from "../../Components/AmberBox";
      import { Input, Select, Button, AutoComplete, Form } from "antd";
      import Axios from "axios";
      import {
          requiredField,
          universalFieldValidation,
          validatePostalCode,
          // Any other needed validations
      } from '../path_to_validations';  // Adjust the path accordingly
      
      const { Option } = Select;
      
      export default function EdytujProjektPage() {
          const [availableGroups, setAvailableGroups] = useState([]);
          const [availableProjects, setAvailableProjects] = useState([]);
          const { id } = useParams();
      
          const [form] = Form.useForm();
      
          const fetchGroups = () => {
              Axios.get("http://localhost:5000/api/grupy", { withCredentials: true })
                  .then((response) => {
                      const transformedData = response.data.grupy.map(grupy => ({
                          name: grupy.Zleceniodawca,
                          value: grupy.id
                      }));
                      setAvailableGroups(transformedData);
                  })
                  .catch((error) => {
                      console.error(error);
                  });
          };
      
          const fetchProjects = () => {
              Axios.get("http://localhost:5000/api/czas/projekty", { withCredentials: true })
                  .then((response) => {
                      const transformedDataProjects = response.data.projekty.map(projekty => ({
                          name: projekty.NazwaKod_Projektu,
                          value: projekty.idProjekty
                      }));
                      setAvailableProjects(transformedDataProjects);
                  })
                  .catch((error) => {
                      console.error(error);
                  });
          };
      
          const fetchProjectData = (projectId) => {
              Axios.get(`http://localhost:5000/api/czas/projekty/${projectId}`, { withCredentials: true })
                  .then((response) => {
                      if (response.data && Array.isArray(response.data) && response.data.length > 0) {
                          const project = response.data[0];
                          form.setFieldsValue({
                              firma: project.Firma_idFirma || '1',
                              zleceniodawca: project.Grupa_urlopowa_idGrupa_urlopowa || '',
                              nazwa: project.NazwaKod_Projektu || '',
                              kodProjektu: project.NazwaKod_Projektu || '',
                              ulica: project.Ulica || '',
                              miejscowosc: project.Miejscowosc || '',
                              kodPocztowy: project.Kod_pocztowy || '',
                              kraj: project.Kraj || ''
                          });
                      }
                  })
                  .catch((error) => {
                      console.error('Error fetching project:', error);
                  });
          };
      
          useEffect(() => {
              fetchGroups();
              fetchProjects();
              fetchProjectData(id);
          }, [id]);
      
          const handleSave = (values) => {
              Axios.put(`http://localhost:5000/api/czas/edytujProjekt/${id}`, values, { 
                  withCredentials: true 
              })
              .then(res => {
                  window.location.href = "/home/projekty";
              })
              .catch(err => {
                  console.error("Error updating project:", err.response ? err.response.data : err.message);
              });
          };
      
          return (
              <div>
                  <div className="w-auto h-auto bg-blue-700 outline outline-1 outline-black flex flex-row items-center space-x-4 m-2 p-3 text-white">
                      <p>Edytuj projekt</p>
                  </div>
                  <AmberBox>
                      <Form form={form} onFinish={handleSave}>
                          <div className="flex flex-col items-center space-y-8 p-4 w-full">
      
                              <div className="w-full md:w-6/12 lg:w-4/12">
                                  <Form.Item
                                      label="Firma"
                                      name="firma"
                                      rules={[requiredField('Firma is required')]}
                                  >
                                      <Select className="w-full" showSearch allowClear>
                                          <Option key={1} value={1}>
                                              PC Husbyggen
                                          </Option>
                                      </Select>
                                  </Form.Item>
                              </div>
      
                              <div className="w-full md:w-6/12 lg:w-4/12">
                                  <Form.Item
                                      label="Zleceniodawca"
                                      name="zleceniodawca"
                                      rules={[requiredField('Zleceniodawca is required')]}
                                  >
                                      <Select className="w-full" showSearch allowClear>
                                          {availableGroups.map((group) => (
                                              <Option key={group.value} value={group.value}>
                                                  {group.name}
                                              </Option>
                                          ))}
                                      </Select>
                                  </Form.Item>
                              </div>
      
                              <div className="w-full md:w-6/12 lg:w-4/12">
                                  <Form.Item
                                      label="Nazwa/Kod Projektu"
                                      name="nazwa"
                                      rules={[requiredField('Nazwa/Kod Projektu is required')]}
                                  >
                                      <AutoComplete
                                          className="w-full"
                                          options={availableProjects.map(project => ({
                                              value: project.name
                                          }))}
                                          placeholder="Wybierz projekt"
                                          filterOption={(inputValue, option) =>
                                              option.value.toLowerCase().includes(inputValue.toLowerCase())
                                          }
                                          allowClear
                                      />
                                  </Form.Item>
                              </div>
      
                              <div className="w-full md:w-6/12 lg:w-4/12">
                                  <Form.Item
                                      label="Ulica"
                                      name="ulica"
                                      rules={[universalFieldValidation('ulica')]}
                                  >
                                      <Input />
                                  </Form.Item>
                              </div>
      
                              <div className="w-full md:w-6/12 lg:w-4/12">
                                  <Form.Item
                                      label="Miejscowość"
                                      name="miejscowosc"
                                      rules={[universalFieldValidation('miejscowość')]}
                                  >
                                      <Input />
                                  </Form.Item>
                              </div>
      
                              <div className="w-full md:w-6/12 lg:w-4/12">
                                  <Form.Item
                                      label="Kod pocztowy"
                                      name="kodPocztowy"
                                      rules={[validatePostalCode]}
                                  >
                                      <Input />
                                  </Form.Item>
                              </div>
      
                              <div className="w-full md:w-6/12 lg:w-4/12">
                                  <Form.Item
                                      label="Kraj"
                                      name="kraj"
                                      rules={[universalFieldValidation('kraj')]}
                                  >
                                      <Input />
                                  </Form.Item>
                              </div>
      
                              <div className="flex space-x-4 mt-8">
                                  <Button type="primary" htmlType="submit">Zapisz</Button>
                                  <Link to="/home/projekty">
                                      <Button>Anuluj</Button>
                                  </Link>
                              </div>
                          </div>
                      </Form>
                  </AmberBox>
              </div>
          );
      }
      
    9. Ensure validation functions are correctly defined: Make sure your validation functions are properly exported and adjusted, especially universalFieldValidation to prevent recursive calls:

      export const universalFieldValidation = (fieldName) => {
          const pattern = /^[A-Za-zÀ-ÖØ-öø-ÿ\s'-]+$/;
          const max = 50;
          const message = `Enter a valid ${fieldName} (max 50 characters)`;
      
          return {
              validator: (_, value) => {
                  if (debugMode) return Promise.resolve();
                  if (value && pattern.test(value) && value.length <= max) {
                      return Promise.resolve();
                  }
                  return Promise.reject(new Error(message));
              },
          };
      };
      
    10. Implement a postal code validation rule if needed: If you don't have a postal code validation, you can create one:

      export const validatePostalCode = {
          validator: (_, value) => {
              const pattern = /^[0-9]{2}-[0-9]{3}$/; // Adjust the pattern as needed
              if (debugMode) return Promise.resolve();
              if (value && pattern.test(value)) {
                  return Promise.resolve();
              }
              return Promise.reject(new Error('Enter a valid postal code (format: xx-xxx)'));
          },
      };
      

    Explanation:

    • By utilizing the Form and Form.Item components from Ant Design, you can seamlessly integrate validation into your inputs without altering the overall structure and styling of your form.
    • The Form.Item component accepts a rules prop where you can pass your custom validation functions.
    • The handleSave function is adjusted to receive the form values from the onFinish event, ensuring the data submitted is the validated data from the form.
    • The useEffect hook and your data fetching functions remain largely unchanged, except for setting form values using form.setFieldsValue().
    • All inputs are wrapped with Form.Item, and appropriate validation rules are applied based on your requirements.

    Note:

    • Ensure that the paths to your validation functions are correctly imported.
    • Test the form thoroughly to make sure validations are working as expected and that the form's appearance remains consistent.

    By following these steps, you integrate validation into your inputs while preserving the frontend composition of your forms.