2
votes

I have a textbox called 'Label' and another select box called 'Validation'. When I click on the add button, the value of the textbox 'Label' appends to the form on left with a newly created textbox like this.

Now what I am trying to do is, I'm trying to add validation to the dynamically created textbox from the list of validation options available in the select box in the form on right(alphabets or numbers).

ie, when I type 'New Age' and select 'Numeric' as validation, the 'New Age:' text box created on the left form should only submit if it input is a number. Otherwise display error.

Thanks in advance.

<!DOCTYPE html>
<html>
<head>
    <!--<link rel="stylesheet" href="styless.css">-->
    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <script>
      var Errors = [];
    </script>
    <script src="newfunc.js"></script>
    <script>
      $(document).ready(function () {
        $("#name").on("input", function () {
          nameCheck();
        });

        $("#age").on("input", function () {
          ageCheck();
        });

        $("#gender").on("input", function () {
          genderCheck();
        });

        $("#vehicle").on("input  ", function () {
          vehicleCheck();
        });

        $("#cars").on("input", function () {
          carsCheck();
        });

        var x = 1;

        function appendRow() {
          var d = document.getElementById('divis');
          d.innerHTML += "<input type='text' id='tst" + x++ + "'><br >";
        }

        $("form[name='form1']").on("submit", function (event) {
          if (!nameCheck()) {
            Errors.push("Please enter a valid name");

            event.preventDefault();
          }
          if (!ageCheck()) {
            Errors.push("Please enter a valid age");
            event.preventDefault();
          }

          if (!genderCheck()) {
            Errors.push("Please select gender");
            event.preventDefault();
          }

          if (!carsCheck()) {
            Errors.push("Please select a valid make");
            event.preventDefault();
            console.log(Errors);
          }

          if (!vehicleCheck()) {
            Errors.push("Please check a mode");
            event.preventDefault();
          } else {

            $(this).trigger("submit");
          }
        });

        $("form[name='form2']").on("submit", function (event) {

          var lab = $("#label").val();
          $('#divis').append(lab);

          appendRow();

          $('#ol_div').append($('#todd'));

          // $('#dono').remove();

          event.preventDefault();

        });
      });
    </script>
    <style>
        .error p {
            display: inline-block;
            color: red;
        }

        form p {
            display: none;
        }

        .inlineinput div {
            display: inline;
        }

        .one {
            display: inline;
        }

        .two {
            display: inline;
        }
    </style>
</head>
<body>
<div class="main" style="width:100%;">
    <div id="old_div" style="float:left; width:50%;">
        <form name="form1" action="fun.php" method="post" onsubmit="validateAllInputBoxes(event);">
            <div class="name">
                <label>Name : </label>
                <input id='name' name='dedede' type='text'><br>
                <p id="p1"></p>
            </div>
            <br>
            <div class="age">
                <label>Age : </label>
                <input id='age' name='subject' type='text'><br>
                <p id="p2"></p>
            </div>
            <br>
            <div class="gender">
                <label>Gender : </label>
                <input id='gender' type='radio' name='sel' value='male'>Male
                <input id='gender' type='radio' name='sel' value='female'>Female<br>
                <p id="p3"></p>
            </div>
            <br>
            <div class="vehicle">
                <label>Vehicle : </label>
                <input type="checkbox" id="vehicle" name='vehicle' value="Car">Car
                <input type="checkbox" id="vehicle" name='vehicle' value="Bike">Bike
                <input type="checkbox" id="vehicle" name='vehicle' value="Other">Other<br>
                <p id="p4"></p>
            </div>
            <br>
            <div class="cars">
                <label>Car Make:</label>
                <select name="cars" id="cars" ">
                <option value="-1" selected disabled="disabled">Choose an option</option>
                <option value="volvo">Volvo</option>
                <option value="saab">Saab</option>
                <option value="fiat">Fiat</option>
                <option value="audi">Audi</option>
                </select>
                <br>
                <p id="p5"></p>
            </div>
            <br>
            <div id="ol_div">
            </div>
            <div>
                <button id="submit" class="sendButton">Submit</button>
            </div>
        </form>
        <br/>
    </div>
    <div style="float:right; width:50%; ">
        <div id="new_div">
            <form name="form2" method="post">
               <span class="inlineinput">
                  <div class="name">
                     <label>Label : </label>
                     <input id='label' name='dedede' type='text'>
                  </div>
               </span>
                <span class="inlineinput">
                  <div class="name">
                     <label>Validation:</label>
                     <select name="vali" id="vali" ">
                        <option value="-1" selected disabled="disabled">Choose an option</option>
                        <option value="1">Numerics</option>
                      </select>
                  </div>
               </span>
                <span class="inlineinput">
                  <div>
                     &nbsp;&nbsp;&nbsp;<button id="dono" class="newButton">Add</button>
                  </div>
               </span>
                <br>
                <br>
                <div id="todd">
                    <div class="one" id="labe"></div>
                    <div class="two" id="divis"></div>
                    <br><br>
                </div>
                <br>
            </form>
        </div>
    </div>
</body>
</html>

newfunc.js

function nameCheck() {
    var name = $('#name').val();
    var name_regex = /^[A-z]+$/;
    if (!name_regex.test(name)) {

        $('#p1').text("* Please enter a valid name *");
        $("#name").parents(".name").addClass("error");
        return false;
    } else {
        $("#name").parents(".name").removeClass("error");
        return true;
    }
}

function ageCheck() {
    var age = $('#age').val();
    var age_regex = /^[0-9]+$/;
    if (!age_regex.test(age)) {
        //Errors.push("Please enter a valid age");
        $('#p2').text("* Please enter a valid age *");
        $("#age").parents(".age").addClass("error");
        return false;
    } else {
        $("#age").parents(".age").removeClass("error");
        return true;
    }
}

function labelCheck() {
    var label = $('#label');

    if (label.val().length > 0) {
        //Errors.push("Please enter a valid age");
        $('#p2').text("* Please enter a valid label *");
        $("#label").parents(".label").addClass("error");
        return false;
    } else {
        $("#label").parents(".label").removeClass("error");
        return true;
    }
}

function genderCheck() {
    var gender = $('#gender').val();

    if ($('input[type=radio]:checked').length <= 0) {
        //Errors.push("Please select Gender");
        $('#p3').text("* Please select the Gender *");
        $("#gender").parents(".gender").addClass("error");
        return false;
    } else {
        $("#gender").parents(".gender").removeClass("error");
        return true;
    }
}

function vehicleCheck() {

    var vehicle = $('#vehicle').val();

    if ($('input[id=vehicle]:checked').length == 0)

    {
        //Errors.push("Please select a vehicle");
        $('#p4').text("* Please select a vehicle *");
        $("#vehicle").parents(".vehicle").addClass("error");
        return false;
    } else {
        $("#vehicle").parents(".vehicle").removeClass("error");
        return true;
    }
}

function carsCheck() {
    var cars = $('#cars').val();

    if (document.form1.cars.value == "-1")

    {
        //Errors.push("Please select one car make");
        $('#p5').text("* Please select one car make *");
        $("#cars").parents(".cars").addClass("error");
        return false;
    } else {
        $("#cars").parents(".cars").removeClass("error");
        return true;
    }
}
(function ($) {
    $.fn.selected = function (fn) {
        return this.each(function () {
            $(this).focus(function () {
                this.dataChanged = false;
            }).change(function () {
                this.dataChanged = true;
                fn(this);
            }).blur(function (e) {
                if (!this.dataChanged) {
                    fn(this);
                }
            });
        });
    };
})(jQuery);
2
I am not able to run this code since nameCheck(); is not defined anywhere , also there are few html issues in code - brk
@brk Sorry, I've edited and added the functions now. - serializer

2 Answers

0
votes

In your case, I would probably add an array called validations and push a new validation function on it every time you add a new text box. On submit, I'd check each function in the validations array and output possible errors. If there was no error, submit, otherwise show the errors.

You could create a function that returns a validation function. For example:

function createNumericValidationForField($yourNewElement) {
  return function () {
    // your logic here, for example:
    try {
      return { result: parseInt($yourNewElement.value()) };
    } catch (err) {
      return { error: err };
    }
  };
}

Then you can go through the validations array, call each of these functions and check if there is a result or error inside the returned objects.

0
votes

Well, you can do this in multiple ways.

1. Write a validation for every input field you want to implement

The most efficient way for this would be to write checks with RegEx like this:

Numbers

const numbers = new RegExp(/^[0-9]+$/);
numbers.test(yourString)

Characters

const characters = new RegExp(/^[a-zA-Z]*$/);
characters.test(yourString);

The test() function returns either true or false when checking your variable against the specified RegExp.

You can do this on every onChange() event the input calls to have a nice and fast response for the user, or you can use it right before submitting the form.

You can add this to the onChange() event while constructing your input field, like this:

var newObject = document.createElement('input');
newObject.onchange = numberValidation();

2. Change the input type when you construct it

As you are dynamically create your label and input fields you can easily change that inputs type:

var newObject = document.createElement('input');
newObject.type = 'password';     // can be password, number, tel, etc.

These input types prevent typing wrong values.