我无法 link 验证和表单提交。需要帮助设置变量(true 或 false)以便不发送空表单?

I can't link validation and form submission. Need help setting the variable (true or false) so that an empty form is not sent?

const form = document.querySelector('.form__contact');
const name = document.querySelector('input[name=name]');
const email = document.querySelector('input[name=email]');
const btnSubmit = document.querySelector('.btn-submit')

双字段验证函数

function checkInputs() {
    let nameValue = name.value.trim();
    let emailValue = email.value.trim();

    if (nameValue === '') {
        setErrorFor(name, 'Name cannot be blank');

    } else if (!isName(emailValue)) {
        setErrorFor(name, 'Not a valid name');
    } else {
        setSuccessFor(name);
    }
    if (emailValue === '') {
        setErrorFor(email, 'Email cannot be blank');

    } else if (!isEmail(emailValue)) {
        setErrorFor(email, 'Not a valid email');

    } else {
        setSuccessFor(email);
    }
}
function setErrorFor(input, message) {
    const inputBox = input.parentElement;
    const errorMessage = inputBox.querySelector('.errors');
    inputBox.className = 'form__field error';
    errorMessage.textContent = message;
}
function setSuccessFor(input) {
    const inputBox = input.parentElement;
    const errorMessage = inputBox.querySelector('.errors');
    inputBox.className = 'form__field success';
    errorMessage.textContent = "";
}

字段验证函数

function isName(name) {
    let regExpName = /^[]{}?/;
    return regExpName.test(name);
}
function isEmail(email) {
    let regExpEmail = /[])?/;
    return regExpEmail.test(email);
}

serialize-这个函数生成一个字符串发送到服务器。函数已经准备好,大,所以我没有把它全部扔在 post

function serialize(form) {
    if (!form || form.nodeName !== "FORM") {
        return false;
    }
    -- ----   - - - - -
}

并提交自己



btnSubmit.addEventListener('click', event => {
    event.preventDefault();

在这里,需要“if else”或“const isValidate = false”的任何其他内容

    checkInputs();
    console.log(serialize(form));

});

"return false" 如果验证错误,试试这个:

function checkInputs() {
  let nameValue = name.value;
  let emailValue = email.value;

  if (!nameValue || nameValue.trim().length() === 0) {
    setErrorFor(name, "Name cannot be blank");
    return false; // return false
  } else if (!isName(emailValue)) {
    setErrorFor(name, "Not a valid name");
    return false; // return false
  } else {
    setSuccessFor(name);
  }

  if (!emailValue || emailValue.trim().length() === 0) {
    setErrorFor(email, "Email cannot be blank");
    return false; // return false
  } else if (!isEmail(emailValue)) {
    setErrorFor(email, "Not a valid email");
    return false; // return false
  } else {
    setSuccessFor(email);
  }

  return true; // default true
}
const isValidate = checkInputs();
if (isValidate) {
  console.log(serialize(form));
}