Как проверить поля для входных значений в многошаговой форме? - PullRequest
2 голосов
/ 05 февраля 2020

Создал форму страницы и проверил наличие пустого значения. Как теперь сделать так, чтобы проверял, что пользователь вводит в поля?

Шаг 1. Имя и Фамилия = проверка (более 2 символов, только буквы без пробелов) и без «-», «/»)

Шаг 2. Номер 1 и Номер 2 = только цифры

Шаг 3. Город и Страна = только буквы

Шаг 4. Электронная почта, телефон и дата = (я сделал маски для даты и телефона), электронная почта этого формата (email@gmail.com)

Вот мой код:

<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="jquery.maskedinput.js"></script>
<style>
 #step2,#step3,#step4,#step5{
        display: none;
       }
 </style>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(e){
   var current = 0;
   $("#Phone").mask("(999) 999-9999");
   $("#date").mask("99.99.9999",{placeholder:"dd.mm.yyyy"});
   $.validator.addMethod("pageRequired", function(value, element) {
            var $element = $(element)
      function match(index) {
                    return current == index && $(element).parents("#step" + (index + 1)).length;
            }
            if (match(0) || match(1) || match(2) || match(3)) {
                return !this.optional(element);
            }
            return "dependency-mismatch";
        },$.validator.messages.required);
        var v = $("#cmaForm").validate({
            errorClass: "warning",
            onkeyup: false,
            onfocusout: false,
            submitHandler: function() {
                alert("Submitted, thanks!");
            }
        });
        $(".next1").click(function() {
            if (v.form()) {
                $("#step2").show();
          $("#step1").hide();
          current = 1;
          $("#progressText").html("Step 2 of 4");
            }
        });
        $(".next2").click(function() {
            if (v.form()) {
                $("#step3").show();
          $("#step2").hide();
          current = 2;
          $("#progressText").html("Step 3 of 4");
            }
        });
        $(".next3").click(function() {
            if (v.form()) {
                $("#step4").show();
          $("#step3").hide();
          current = 3;
           $("#progressText").html("Step 4 of 4");
            }
        });

});
</script>
<div id="progressText">Step 1 of 4</div>
<form id="cmaForm" action="" method="post">
<ul id="stepForm">
<li id="step1">
<p>
<label>First name:</label>
<input type="text" name="fname" class="pageRequired"></p>
<p>
<label>Last name:</label>
<input type="text" name="lname" class="pageRequired"></p>
<p class="buttonWrapper">
                                <input name="formNext1" type="button" class="next1 nextbutton" value="Next" alt="Next" title="Next">
            </p>
</li>
<li id="step2">
<p>
<label>Number1:</label>
<input type="text" name="num1" class="pageRequired" title="Enter number 1"></p>
<p>
<label>Number2:</label>
<input type="text" name="num2" class="pageRequired" title="Enter number 2"></p>
<p class="buttonWrapper">
                                <input name="formNext1" type="button" class="next2 nextbutton" value="Next" alt="Next" title="Next">
            </p>
</li>
<li id="step3">
<p>
<label>City:</label>
<input type="text" name="city" class="pageRequired"></p>
<p>
<label>Country:</label>
<input type="text" name="country" class="pageRequired"></p>
<p class="buttonWrapper">
                                <input name="formNext1" type="button" class="next3 nextbutton" value="Next" alt="Next" title="Next">
            </p>
</li>
<li id="step4">
<p><label>Email Address:</label><input name="email" id="email" class="pageRequired" title="Email address is required"></p>
<p><label>Phone Number:</label><input name="Phone" id="Phone" class="pageRequired" maxlength="254" title="Phone Number is required"></p>
<p><label>Date:</label>
    <input type="text" name="date" id="date" class="sum pageRequired" title="Date is required"></p>
<input type="submit" class="submitbutton" value="Submit">
</li>
</ul>
</form>
</html>
</body>

Ответы [ 2 ]

1 голос
/ 05 февраля 2020

Попробуйте использовать

$("#step2").css("visibility", "hidden");
$("#step3").css("visibility", "visible");

Вместо

$("#step2").hide()
$("#step3").show();

Дайте вашим входам уникальный идентификатор

<p>
<label>Number1:</label>
<input type="text" name="num1" id="num1" class="pageRequired" title="Enter number 1"></p>

Таким образом, вы все равно можете прочитать входные значения.

$("#num1").val();

Но вы также можете получить все значения, используя обычную форму отправки.

0 голосов
/ 06 февраля 2020

Нашли способ сделать. Код на js:

$.validator.addMethod("minlenghtname", function (value, element) {
        return /^[a-zа-я]+$/i.test(value);
    }," does not match the format");

$.validator.addMethod("requiredname", function (value, element) {
        return value.length > 2;
    }," Fill this field !!!");
$.validator.addMethod("requirednum", function (value, element) {
        return /^\d+$/i.test(value);
    }," only numbers");
$.validator.addMethod("requiredemail", function (value, element) {
        return /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);
    }," Invalid email");
$.validator.addMethod("checkMask", function(value, element) {
     return /\+\d{1}\(\d{3}\)\d{3}-\d{4}/g.test(value); 
},"Invalid phone format (+9(999)999-9999)");
$.validator.addMethod("checkData", function(value, element) {
     return value.match(/^\d\d?\.\d\d?\.\d\d\d\d$/);
},"Please enter a date in the format mm.dd.yyyy.");



$(function () {
$("#Phone").mask("+9(999)999-9999");
$("#date").mask("99.99.9999",{placeholder:"mm.dd.yyyy"});

 var v = $("#commentForm").validate({
        rules: {
            fname: {
                requiredname: true,
                minlenghtname: true
            },
            lname: {
                requiredname: true,
                minlenghtname: true
            },
            num1:{
                requirednum:true
            },
            num2: {
                requirednum:true
            },
            city: {
               minlenghtname: true
            },
            country:{
               minlenghtname: true
            },
            email:{
               requiredemail: true
            },
            Phone:{
              checkMask: true
            },
            date:{
              checkData: true
            }
        },
        submitHandler: function() {
                alert("Submitted, thanks!");
            }

    })

    $(".next1").click(function() {
            if (v.form()) {
                $("#step2").show();
                $("#step1").hide();
                 $("#progressText").html("Step 2 of 4");

            }
      });
     $(".next2").click(function() {
            if (v.form()) {
                $("#step3").show();
                $("#step2").hide();
                $("#progressText").html("Step 3 of 4");
            }
        });
     $(".next3").click(function() {
            if (v.form()) {
                $("#step4").show();
                $("#step3").hide();
                $("#progressText").html("Step 4 of 4");

            }
        });
});

Вот демонстрационная ссылка: многоступенчатая форма

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...