JavaScript 表单(ajax 提交)验证做一些时髦的事情

JavaScript form (ajax submission) with validation doing something funky

我正在尝试使用 ajax 提交来执行表单验证功能。由于某种原因,验证不起作用,当它提交时,我的服务器得到空字段(当我测试验证时)但它表明它试图 post 到同一页面......我不不知道为什么。

表格:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<form id='form' novalidate method="post" class='m-2 p-1'>
  <div class='row'>
    <div class='col p-1'>
      <div class="form-floating mb-3">
        <input required type="text" name='First Name' class="form-control" id="fname" placeholder="First Name">
        <label for="fname">First Name<span class='red' aria-label='required'> *</span></label>
      </div>
    </div>
    <div class='col p-1'>
      <div class="form-floating mb-3">
        <input required type="text" name='Last Name' class="form-control" id="lname" placeholder="Last Name">
        <label for="lname">Last Name</label>
      </div>
    </div>
  </div>
  <div class='row'>
    <div class='col p-1'>
      <div class="form-floating mb-3">
        <input required type="email" name='Email' class="form-control" id="email" placeholder="Email">
        <label for="lname">Email <span class='red' aria-label='required'> *</span></label>
      </div>
    </div>
    <div class='col p-1'>
      <div class="form-floating mb-3">
        <select required name='Reason For Contacting' class="form-control" id="reason" placeholder="Reason For Contacting">
          <option value='Feedback' selected>Feedback</option>
          <option value='other'>Other</option>
        </select>
        <label for="why">Reason For Contacting<span class='red' aria-label='required'> *</span></label>
      </div>
    </div>
  </div>
  <div class='row'>
    <div class='col p-1'>
      <div class="form-floating mb-3">
        <textarea required name='Comments' class="form-control" id="comment" placeholder="Your Comments"></textarea>
        <label for="comment">Your Comments<span class='red' aria-label='required'> *</span></label>
      </div>
    </div>
  </div>
  <div class='row'>
    <div class='col p-1'>
      <button class='form-control btn btn-outline-primary' id='submit'>Send</button>
    </div>
  </div>
</form>

我的 JS 文件:

$(document).ready(() => {
  autosize($('textarea'))
  $('#submit').click((e) => {
    if (validate() == true) {
      sendForm();
    } else {
      error(validate())
    }
  })
})
var errors;
window.onerror = function(msg, url, linenumber) {
  alert('Error message: ' + msg + '\nURL: ' + url + '\nLine Number: ' + linenumber);
  return true;
}

function validate() {
  elements = $(':input')
  elements.each((element) => {
    element = $(element).get()
    if (element.value === '' || !email(element)) {
      errors += element.name + " is invalid."
    } else {
      return;
    }
  })
  if (errors) {
    return errors
  } else true;
}

function sendForm() {
  name = $('input[name="First Name"]').val().trim() + " " + $('input[name="Last Name"]').val().trim()
  email = $('input[name="Email"]').val().trim()
  why = $("select").val().trim()
  comments = $('textarea').val().trim()
  data = {
    "name": name,
    "email": email,
    "reason": why,
    "text": comments
  }
  $.ajax({
    type: 'POST',
    url: 'https://admin.bekesbikes.tk/contact',
    crossDomain: true,
    data: data,
    dataType: 'json',
    success: (responseData, textStatus, errorThrown) => {
      new Notify({
        title: 'Submitted!',
        text: 'Your feedback has been recorded!\n\nWe will get back to your email shortly!\n\nHope to see you soon!',
        effect: 'slide',
        status: 'success',
        speed: 1000,
        autoclose: true
      })
      $(':input').val('');
      $('select').val('Feedback')
    },
    error: (responseData, textStatus, errorThrown) => {
      new Notify({
        title: 'Could not submit!',
        text: 'The form could not be submitted.\n\nPlease try again or come back later!\n\nSorry for the inconvenience.',
        effect: 'slide',
        customIcon: "<img src='https://www.flaticon.com/svg/vstatic/svg/753/753345.svg?token=exp=1616679486~hmac=4f66bb69b263e9e4d9be5038a16cc41d' width='50px'>",
        status: 'error',
        speed: 1000,
        autoclose: true
      })
    }
  });
}

function error(text) {
  new Notify({
    title: 'Form Fields Are Not Correct',
    text: text,
    effect: 'slide',
    status: 'info',
    speed: 1000,
    autoclose: true
  })
}

function send() {
  if (validate()) {
    sendForm()
  } else {
    error(validate())
  }
}

function email(element) {
  if (element.type === 'email' && /^[^\s@]+@[^\s@]+$/.text(element.value)) {
    return true;
  } else if (element.type !== 'email') {
    return true;
  } else {
    return false;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

我提交的时候去了哪里(表格在这个URL):

知道我应该做什么吗?

Note I am using node.js with express.js.

编辑

我添加了:e.preventDefault() 到我的提交事件处理程序,但现在当我提交表单而不填写任何内容时,我收到此通知:

我更改了您的点击处理程序:

  • 默认预防,
  • validate() 作为变量,以便它只运行一次,

错误声明

  • 空字符串而不是未定义,

你的 validate() 函数

  • 使用 :not(),
  • 排除按钮
  • 箭头函数改为普通匿名函数,
  • 用这个代替了元素,它只是一个索引,
  • 在else最后加了一个return,

和您的 email() 函数

  • 将电子邮件验证外包给自己的函数。

我也删除了 send(),因为它没有被使用,在 sendForm() 中用 var 声明变量并添加了很多分号 -> 也许你的代码中已经缺少一个,你希望 js 纠错将自动添加它们...

最后,我将参数 showIcon 添加到您的 Notify 对象(那是 'undefined' 部分;)

$(document).ready(() => {

  autosize($('textarea'))
    
    $('#form').submit((e) => {
        e.preventDefault();
        var validated = validate();
        if (validated == true) {
            sendForm();
        } else error(validated);
    });
    
    var errors = '';

    window.onerror = function(msg, url, linenumber) {
        alert('Error message: ' + msg + '\nURL: ' + url + '\nLine Number: ' + linenumber);
        return true;
    }

    function validate() {
        elements = $(':input:not(button)');
        elements.each(function() {
            if (this.value === '' || !email(this)) {
                errors += this.name + " is invalid.";
            } else return;
        });
        if (errors) {
            return errors;
        } else return true;
    }

    function sendForm() {
        var name = $('input[name="First Name"]').val().trim() + " " + $('input[name="Last Name"]').val().trim();
        var email = $('input[name="Email"]').val().trim();
        var why = $("select").val().trim();
        var comments = $('textarea').val().trim();
        var data = {
            "name": name,
            "email": email,
            "reason": why,
            "text": comments
        };
        $.ajax({
            type: 'POST',
            url: 'https://admin.bekesbikes.tk/contact',
            crossDomain: true,
            data: data,
            dataType: 'json',
            success: (responseData, textStatus, jqXHR) => {
                new Notify({
                    title: 'Submitted!',
                    text: 'Your feedback has been recorded!\n\nWe will get back to your email shortly!\n\nHope to see you soon!',
                    effect: 'slide',
                    status: 'success',
                    speed: 1000,
                    autoclose: true,
                    showIcon: false
                });
                $(':input').val('');
                $('select').val('Feedback');
            },
            error: (jqXHR, textStatus, errorThrown) => {
                new Notify({
                    title: 'Could not submit!',
                    text: 'The form could not be submitted.\n\nPlease try again or come back later!\n\nSorry for the inconvenience.',
                    effect: 'slide',
                    customIcon: "<img src='https://www.flaticon.com/svg/vstatic/svg/753/753345.svg?token=exp=1616679486~hmac=4f66bb69b263e9e4d9be5038a16cc41d' width='50px'>",
                    status: 'error',
                    speed: 1000,
                    autoclose: true,
                    showIcon: true
                });
            }
        });
    }

    function error(text) {
        new Notify({
            title: 'Form Fields Are Not Correct',
            text: text,
            effect: 'slide',
            status: 'info',
            speed: 1000,
            autoclose: true,
            showIcon: false
        })
    }

    function validateEmail(email) {
        const re = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
    }

    function email(element) {
        if (element.type === 'email' && validateEmail(element.value)) {
            return true;
        } else if (element.type !== 'email') {
            return true;
        } else return false;
    }
    
});