3

 avatar
unknown
javascript
a year ago
1.7 kB
8
Indexable
function solution() {
  // Find the form element in the DOM
  const form = document.querySelector('form');

  // Find the radio buttons for "person" and "company"
  const personRadio = document.querySelector('input[name="type"][value="person"]');
  const companyRadio = document.querySelector('input[name="type"][value="company"]');

  // Find the input fields for validation
  const firstNameInput = document.querySelector('input[name="first_name"]');
  const lastNameInput = document.querySelector('input[name="last_name"]');
  const emailInput = document.querySelector('input[name="email"]');
  const companyNameInput = document.querySelector('input[name="company_name"]');
  const phoneInput = document.querySelector('input[name="phone"]');

  // Check if the "person" radio button is selected
  if (personRadio.checked) {
    // Validate first_name and last_name
    const firstName = firstNameInput.value.trim();
    const lastName = lastNameInput.value.trim();
    const email = emailInput.value.trim();

    const isFirstNameValid = firstName.length > 0;
    const isLastNameValid = lastName.length > 0;
    const isEmailValid = /^[\w.-]+@[A-Za-z\d.-]+\.[A-Za-z]{2,}$/.test(email);

    return isFirstNameValid && isLastNameValid && isEmailValid;
  } else if (companyRadio.checked) {
    // Validate company_name and phone
    const companyName = companyNameInput.value.trim();
    const phone = phoneInput.value.trim();

    const isCompanyNameValid = companyName.length > 0;
    const isPhoneValid = /^[0-9\s-]+$/.test(phone) && phone.replace(/[\s-]/g, '').length >= 6;

    return isCompanyNameValid && isPhoneValid;
  }

  // If neither "person" nor "company" is selected, the form is invalid
  return false;
}
Editor is loading...
Leave a Comment