简体   繁体   中英

jQuery Dynamic form input validation

This question is based off of another StackOverflow question found here .

My goal is to build simple validation that ensures input fields are filled in sequential order based on their index (natural flow).

» The main complexity is that I'm trying to consolidate validation across different types of input.

» Specifically, radio button groups should be validated as one entity. When using the .prev() and .next() methods, the gender radio group should move to essay or age respectively, not male or female.

» The next bug is that I cannot get the age row to properly disable if the content in any previous row is undone/removed. It does not work consistently and I cannot figure out why.

» The validate button should make items that are filled in green, otherwise highlight them in red color.

If there is a more refined approach to this please feel free to elaborate. If there are easier selectors that I could be utilizes to build up the arrays for more streamlined manipulation and validation, please also enlighten me and share.

Almost Working Example

 //StackOverflow Question - https://stackoverflow.com/q/37618826/5076162 [06-03-2016] //Step 1: Declare the collection of all inputs that should be manipulated. var $inputFields = $('textarea, input[type="text"], input[type="number"], input[type="radio"]'); //Step 2: Insert the collection into a single array using the .push() method. var arr = []; $inputFields.each(function() { arr.push($(this)); }); //Step 3: Iterate through the newly created array and perform certain functions. //Source - https://stackoverflow.com/a/5437904/5076162 $.each(arr, function(i) { if (i > 0) { $(this).attr('readonly', 'readonly').addClass('disabled'); $(':radio[readonly]:not(:checked)').attr('disabled', true); //console.log("Iteration number: " + i); } }); var $justRadio = $('input[type="radio"]:disabled'); //Step 4: Detect input and apply logic for each situation. Note that different input types require different syntax. $inputFields.on("propertychange input change focus blur", function(i) { var index = $inputFields.index(this); var next = $inputFields.eq(index + 1); var $checkedRadio = $('input[type="radio"]:checked').length; var radioCounter = $justRadio.length; if ($(this).val() === "") { $inputFields.filter(function() { return $inputFields.index(this) > index; }).attr("readonly", true).attr('disabled', true).addClass('disabled'); //console.log('disable Fired'); } else { next.attr("readonly", false).attr('disabled', false).removeClass('disabled'); $justRadio = $('input[type="radio"]:disabled'); //console.log(radioCounter); if (radioCounter < 2) { $justRadio.closest('tr').find($justRadio).attr("readonly", false).attr('disabled', false).removeClass('disabled'); } } if ($checkedRadio > 0 && $justRadio.length === 0) { $inputFields.last().attr("readonly", false).attr('disabled', false).removeClass('disabled'); //console.log("This fired: lastRow"); } //Step 5: Implement a user interface button so they know they have filled in all fields. var emptyCount = 0; $inputFields.not($('input[type="radio"]')).each(function() { if ($(this).val() === "") { emptyCount = +1; } //console.log("Empty Count: " + emptyCount); }); var vRCount = 0; $inputFields.not($('input[type="text"], input[type="number"], textarea')).each(function() { if ($(this).is(":checked")) { vRCount = +1; } //console.log("Empty Count: " + emptyCount); }); $('input.validateCheck').on("click", function() { if (emptyCount === 0 && vRCount > 0) { $inputFields.closest('tr').find('td').css("color", "green"); $('input.validateCheck').text("Success!").attr("value", "Success!"); } }); }); 
 table { border-collapse: collapse; } td { vertical-align: top; border: solid 1px #ACE; padding: 2px; font-family: arial; } input { width: 450px; text-align: center; } textarea { margin: 0; width: 448px; text-align: left; } input[type="radio"] { width: 15px; } div.gender { display: inline-block; clear: none; width: 219px; } .disabled { background-color: #f1f1f1; } input[type="button"] { width: 546px; margin-top: 5px; color: #FFF; background-color: red; border: solid 1px #ACE; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <form> <table> <tr> <td>First name:</td> <td> <input type="text" name="firstname"> </td> </tr> <tr> <td>Last name:</td> <td> <input type="text" name="lastname"> </td> </tr> <tr> <td>Essay:</td> <td> <textarea rows="4" cols=""></textarea> </td> </tr> <tr> <td>Gender:</td> <td> <div class='gender'> <input type="radio" name="gender" value="male">Male</div> <div class='gender'> <input type="radio" name="gender" value="female">Female</div> </td> </tr> <tr> <td>Age:</td> <td> <input type="number" name="age" min="18" max="99"> </td> </tr> </table> <input class='validateCheck' type="button" value="Validate" /> </form> 

Use HTML5 form validations. It is a lot easier and faster. Hope this helps...

    <style>

    form{font-size:100%;min-width:560px;max-width:620px;width:590px;margin:0 auto;padding:0}
    form fieldset{clear:both;font-size:100%;border-color:#000;border-style:solid none none;border-width:1px 0 0;margin:0;padding:10px}
    form fieldset legend{font-size:150%;font-weight:400;color:#000;margin:0;padding:0 5px}
    label{font-size:100%}
    label u{font-style:normal;text-decoration:underline}
    input,select,textarea{font-family:Tahoma, Arial, sans-serif;font-size:100%;color:#000}

    input:required ,select:required, textarea:required, radio:required{
        font-family:Tahoma, Arial, sans-serif;
        font-size:100%;
        color:#000; 
        border-color:red;
        background: #fff url(images/red-asterisk.png) no-repeat 98% center;
    }

    input:focus ,select:focus, textarea:focus, radio:focus{
        background: #fff url(invalid.png) no-repeat 98% center;
        box-shadow: 0 0 5px #d45252;
        border-color: #b03535
    }

    input:valid ,select:valid, textarea:valid, radio:valid{
        background: #fff url(valid.png) no-repeat 98% center;
        box-shadow: 0 0 5px #5cd053;
        border-color: #28921f;

    }


    :valid {box-shadow:  0 0 5px green}
    :-moz-submit-invalid {box-shadow:  0 0 5px pink}



</style>

        <form>
      <table>
        <tr>
          <td>First name:</td>
          <td>
              <input type="text" id="firstname" name="firstname" required>
          </td>
        </tr>
        <tr>
          <td>Last name:</td>
          <td>
            <input type="text" name="lastname" required>
          </td>
        </tr>
        <tr>
          <td>Essay:</td>
          <td>
            <textarea rows="4" cols="20" required></textarea>
          </td>
        </tr>
        <tr>
          <td>Gender:</td>
          <td>
            <div class='gender'>
              <input type="radio" name="gender" value="male" required> Male</div>
            <div class='gender'>
              <input type="radio" name="gender" value="female" required> Female</div>
          </td>
        </tr>
        <tr>
          <td>Age:</td>
          <td>
            <input type="number" name="age" min="18" max="99" required>
          </td>
        </tr>
      </table>
      <input class='validateCheck' type="submit" value="Validate" />
    </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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