JavaScript表单( AJAX 提交),带有验证,做一些时髦的事情

quhf5bfb  于 2023-01-04  发布在  Java
关注(0)|答案(1)|浏览(141)

我正在尝试用Ajax提交一个表单验证功能。由于某种原因,验证不起作用,当它提交时,我的服务器得到了空字段(当我测试验证时),但它显示它试图发布到同一个页面...我不知道为什么。
表格:

<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文件:
x一个一个一个一个x一个一个二个x
提交时的位置(表单位于此URL):

你知道我应该怎么做吗?我正在使用node.jsexpress.js
我在submit事件处理程序中添加了:e.preventDefault(),但是现在当我提交表单而不填写任何内容时,我会收到以下通知:

o8x7eapl

o8x7eapl1#

我修改了你的点击处理程序:

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

错误声明

  • 空字符串而不是undefined,

validate()函数

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

和email()函数

  • 将电子邮件验证外包给自己的职能部门。

我还删除了send(),因为它没有被使用,用var声明了sendForm()中的变量,并添加了许多分号-〉也许在您的代码中已经缺少了一个,您希望js错误纠正会自动添加它们...
最后,我将参数showIcon添加到您的Notify对象中(这是“未定义”部分;)

$(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;
    }
    
});

相关问题