1

I created a form where the fields are validated:title,name,age,email,description и text. There are still fields that you can add. They also need to be validated, namely the number of characters. How to do validation through a loop? For all fields, and so that an error is displayed near each unfilled field. It is also necessary to take into account that the user can delete all fields with one button and reset the field counter, which is added after each added field. Here is the code

<html>
<head>
<title>Dynamically add input field using jquery</title>
<style>
.container1 input[type=text] {
padding:5px 0px;
margin:5px 5px 5px 0px;
}


.add_form_field
{
    background-color: #1c97f3;
    border: none;
    color: white;
    padding: 8px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
    border:1px solid #186dad;

}

input{
    border: 1px solid #1c97f3;
    width: 260px;
    height: 40px;
    margin-bottom:14px;
}

.delete{
    background-color: #fd1200;
    border: none;
    color: white;
    padding: 5px 15px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 14px;
    margin: 4px 2px;
    cursor: pointer;

}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
    var max_fields      = 10;
    var wrapper         = $(".container1"); 
    var add_button      = $(".add_form_field"); 
    var error_desc = false;
    var error_text = false;
    var x = 1; 
    $(add_button).click(function(e){ 
        e.preventDefault();
        if(x < max_fields){ 
            x++; 
            $(wrapper).append('<div class="driver__list"><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box
        }
        else
        {
        alert('You Reached the limits')
        }
    });

    $(wrapper).on("click",".delete", function(e){ 
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })

     $('#clear').click(function(){   
      x = 0;  
      $("input").closest('.container1').find('.driver__list').html('');
     });
    $('#age').keypress('', function () {
      check_char(/^\d+$/,"#age","#age_error_message","Only numbers");
    });

    //https://stackoverflow.com/questions/6646613/please-explain-this-e-mail-validation-regular-expression
    $('#email').keypress('', function () {
      check_char(/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i,"#email","#email_error_message","Invalid email");
    });
    $('#name').keypress('', function () {
      check_char(/^[a-zA-Z]*$/,"#name","#name_error_message","Text at least 7 characters");

    });
    $('#title').keypress('', function () {
      check_field("#title","#title_error_message",7,"Text at least 7 characters");
    });
    $('#description').keypress('', function () {
      check_field("#description","#desc_error_message",200,"Text at least 200 characters");
    });
    $('#text').keypress('', function () {
      //check_text();
      check_field("#text","#text_error_message",200,"Text at least 200 characters");
    });

    function check_char(pattern,id,err,mess)
    {
      var text = $(id).val();
      if (pattern.test(text) && text !== '') {
               $(err).hide();
               $(id).css("border-bottom","2px solid #34F458");
      } else {
               $(err).html(mess);
               $(err).show();
               $(id).css("border-bottom","2px solid #F90A0A");
       }
    }

    function check_field(id,err,len,mess)
    {

      var text = $(id).val();
      if (text.length>len) {
        $(err).hide();
        $(id).css("border-bottom","2px solid #34F458");
      }else
      {
         $(err).html(mess);
         $(err).show();
         $(id).css("border-bottom","2px solid #F90A0A");
      }
    }

});
</script>
</head>
<body>
<span id="mess"></span>

<div id="content">
<form name="add_name" id="add_name"> 
    Title:<br>
    <input type="text" id="title" name="title"><br>
    <span class="error_form" id="title_error_message"></span>
    Name:<br>
    <input type="text" id="name" name="name"><br>
    <span class="error_form" id="name_error_message"></span>
    Age:<br>
    <input type="text" id="age" name="age"><br>
    <span class="error_form" id="age_error_message"></span>
    Email:<br>
    <input type="text" id="email" name="email"><br>
    <span class="error_form" id="email_error_message"></span>
<div class="container1">
<button class="add_form_field">Add New Field &nbsp; <span style="font-size:16px; font-weight:bold;">+ </span></button><button id="clear">Clear</button>

    <div class="driver__list"><input type="text" name="mytext[]"></div>
</div>
Description:<br>
<textarea cols="50px" id="description" rows="15px" name="description"></textarea><br>
<span class="error_form" id="desc_error_message"></span>
Text:<br>
<textarea cols="50px" id="text" rows="15px" name="text"></textarea><br>
<span class="error_form" id="text_error_message"></span><br>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</form>
</div>
</body>
</html>
Lex34
  • 75
  • 6

1 Answers1

0

Why should you validate it this way? Validation rules like field length can be defined with HTML data- attributes:

<input type="text" name="surname" minlength="4" maxlength="15" data-toggle-validation="1">

After that you can just bind a event listener on input elements with data-toggle-validation attribute:

$('#content > form#add_name').on('change', 'input[data-toggle-validation="1"]', function() {
   ...
});

Also, don't forget about HTML-validation too.

  • I’m just going to add another field to the person’s age. When dynamically adding fields will be added another field with age. This field also needs to be checked, so that the user enters numbers. How to be in this case? – Lex34 Jan 26 '20 at 02:45
  • @Lex34 Delegated event handlers can be bound to elements not presented at the time. My example should work fine with condition that your field will have `data-toggle-validation="1"` attribute. – Alexander Zinchenko Jan 26 '20 at 12:33