简体   繁体   English

如何更改 java 脚本中表单字段的验证

[英]How to change the validation of form fields in java script

I have a ready-made form for sending messages to the mail, here is a link to github: validation and sending messages to the mail For validation I use The old version of validation v 1.5我有一个现成的用于向邮件发送消息的表格,这里是 github 的链接:验证和向邮件发送消息为了验证,我使用旧版本的验证 v 1.5

Please help with the validation of the fields.请帮助验证字段。 The problem is this:问题是这样的:

  1. When validating a field named line 78 of the scripts file.js doesn't work.验证脚本 file.js 中名为第 78 行的字段时不起作用。 There is a limit for the name field of 7 characters, but validation uses its own internal rules for a minimum of 2 characters.名称字段有 7 个字符的限制,但验证使用其自己的内部规则最少 2 个字符。
  2. The phone validation log does not output a log from the 85th line of the file scripts.js, although in theory it should print the phone number without spaces, hyphens and brackets电话验证日志不是 output 文件 scripts.js 的第 85 行的日志,尽管理论上它应该打印不带空格、连字符和括号的电话号码
  3. Phone validation does not occur (lines 81-88 of the file scripts.js ).不会进行电话验证(文件 scripts.js 的第 81-88 行)。 I specified the data-validate-field field with the value tel and specified a function that would return true for this tel.我用值 tel 指定了 data-validate-field 字段,并指定了一个 function,它将为此 tel 返回 true。 But this rule doesn't work either.但这条规则也不起作用。

Why doesn't this particular part of the code work?为什么代码的这个特定部分不起作用?

validateForms('.form', {
    rules: {
      name: {
        required: true,
        minLength: 7,
        maxLength: 30,
      },
      tel: {
        tel: true,
        function: (name, value) => {
          const phone = document.querySelector('input[type="tel"]').inputmask.unmaskedvalue()
          console.log(phone)
          return Number(phone) && phone.length === 10
        }
      },
      email: {required: true, email: true},

    },
  }, messages, '.thanks-popup', 'send goal');

Please help me solve 3 problems.请帮我解决3个问题。 HTML code HTML代码

<!DOCTYPE html>
<html lang="ru">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <form action="mail.php" enctype="multipart/form-data" class="form" method="POST">
            <input type="hidden" name="admin_email[]" value="any@mail.ru">
            <input type="hidden" name="form_subject" value="Тема письма">
            <h2>Отправка формы</h2>
            <label class="form-label">
                <span>Введите имя</span>
                <input type="text" data-validate-field="name" name="name" required>
            </label>
            <label class="form-label">
                <span>Введите телефон</span>
                <input type="tel" data-validate-field="tel" name="tel" required>
            </label>
            <label class="form-label">
                <span>Введите email</span>
                <input type="email" data-validate-field="email" name="email" required>
            </label>
            <label class="form-label file-label">
                <span>Прикрепить файл</span>
                <input type="file" name="file[]" multiple>
            </label>
            <button type="submit">Отправить</button>
        </form>
        <script src="inputmask.min.js"></script>
        <script src="just-validate.min.js"></script>
        <script src="script.js"></script>
    </body>
</html>

File code script.js文件代码script.js

let selector = document.querySelectorAll('input[type="tel"]');
let im = new Inputmask('+7 (999) 999-99-99');
im.mask(selector);

let selector2 = document.querySelector('input[type="tel"]');

selector2.addEventListener('input', function(){
    console.log(selector2.value)


    const re = /^\d*(\.\d+)?$/

    console.log(selector2.value.match(/[0-9]/g).length)


    console.log(selector2.value.replace(/[0-9]/g, "0"));
    
});

const fileInput = document.querySelector('input[type="file"]');

fileInput.addEventListener('change', (e) => {
    let files = e.currentTarget.files;
    console.log(files);

    if (files.length) {
        fileInput.closest('label').querySelector('span').textContent = files[0].name;
    } else {
        fileInput.closest('label').querySelector('span').textContent = 'Прикрепить файл';
    }

});

let validateForms = function(selector, rules, messages, successModal, yaGoal) {
    new window.JustValidate(selector, {
        rules: rules,
        messages: messages,
        submitHandler: function(form) {
            let formData = new FormData(form);

            let xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        console.log('Отправлено');
                    }
                }
            }

            xhr.open('POST', 'mail.php', true);
            xhr.send(formData);

            form.reset();

            fileInput.closest('label').querySelector('span').textContent = 'Прикрепить файл';
        }
    });
}

// validateForms('.form', { email: {required: true, email: true}, tel: {required: true} }, '.thanks-popup', 'send goal');
let messages = {
    name: {
      required: "Вы не ввели имя",
      minLength: "Имя должно иметь более 3 символов",
      maxLength: "Имя должно быть менее 30 символов",
    },
    tel: {
      required: "Неверный формат номера",
      tel: "Введите телефон",
    },
}

  validateForms('.form', {
    rules: {
      name: {
        required: true,
        minLength: 7,
        maxLength: 30,
      },
      tel: {
        tel: true,
        function: (name, value) => {
          const phone = document.querySelector('input[type="tel"]').inputmask.unmaskedvalue()
          console.log(phone)
          return Number(phone) && phone.length === 10
        }
      },
      email: {required: true, email: true},

    },
  }, messages, '.thanks-popup', 'send goal');

enter image description here在此处输入图像描述

74 file line script.js should be changed to new JustValidate('.form', { The entire file code will look like 74 文件行 script.js 应该更改为new JustValidate('.form', {整个文件代码看起来像

let selector = document.querySelectorAll('input[type="tel"]');
let im = new Inputmask('+7 (999) 999-99-99');
im.mask(selector);

let selector2 = document.querySelector('input[type="tel"]');

selector2.addEventListener('input', function(){
    console.log(selector2.value)


    const re = /^\d*(\.\d+)?$/

    console.log(selector2.value.match(/[0-9]/g).length)


    console.log(selector2.value.replace(/[0-9]/g, "0"));
    
});

const fileInput = document.querySelector('input[type="file"]');

fileInput.addEventListener('change', (e) => {
    let files = e.currentTarget.files;
    console.log(files);

    if (files.length) {
        fileInput.closest('label').querySelector('span').textContent = files[0].name;
    } else {
        fileInput.closest('label').querySelector('span').textContent = 'Прикрепить файл';
    }

});

let validateForms = function(selector, rules, messages, successModal, yaGoal) {
    new window.JustValidate(selector, {
        rules: rules,
        messages: messages,
        submitHandler: function(form) {
            let formData = new FormData(form);

            let xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        console.log('Отправлено');
                    }
                }
            }

            xhr.open('POST', 'mail.php', true);
            xhr.send(formData);

            form.reset();

            fileInput.closest('label').querySelector('span').textContent = 'Прикрепить файл';
        }
    });
}

// validateForms('.form', { email: {required: true, email: true}, tel: {required: true} }, '.thanks-popup', 'send goal');
let messages = {
    name: {
      required: "Вы не ввели имя",
      minLength: "Имя должно иметь более 3 символов",
      maxLength: "Имя должно быть менее 30 символов",
    },
    tel: {
      required: "Неверный формат номера",
      tel: "Введите телефон",
    },
}

new JustValidate('.form', {
    rules: {
      name: {
        required: true,
        minLength: 7,
        maxLength: 30,
      },
      tel: {
        tel: true,
        function: (name, value) => {
          const phone = document.querySelector('input[type="tel"]').inputmask.unmaskedvalue()
          console.log(phone)
          return Number(phone) && phone.length === 10
        }
      },
      email: {required: true, email: true},

    },
}, messages, '.thanks-popup', 'send goal');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM