jQuery动态表单输入验证

时间:2016-06-03 20:24:20

标签: javascript jquery forms validation input

此问题基于另一个找到的StackOverflow问题here

我的目标是构建简单的验证,确保输入字段根据其索引(自然流)按顺序填充。

»主要的复杂性是我正在尝试整合不同类型输入的验证。

»具体而言,单选按钮组应验证为一个实体。使用.prev().next()方法时,性别广播组应分别转到论文或年龄,而不是男性或女性。

»下一个错误是,如果任何前一行中的内容被撤消/删除,我无法正确禁用年龄行。它不能始终如一地工作,我无法弄清楚原因。

»验证按钮应该使用绿色填充的项目,否则用红色突出显示它们。

如果有更精确的方法,请随时详细说明。如果我可以利用更容易的选择器来构建阵列以进行更简化的操作和验证,请同时启发并分享。

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>

1 个答案:

答案 0 :(得分:1)

使用HTML5表单验证。它更容易,更快捷。希望这会有所帮助...

    <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>
相关问题