避免使用 jQuery 绕过 maxlength 属性

Avoid bypassing maxlength attribute using jQuery

我在尝试绕过 textarea 字段中的最大长度值来验证用户时遇到问题,但我的验证似乎 none 有效。我正在尝试验证用户是否可以将最大长度更改为超过我们的初始限制,或者是否从元素中删除了最大长度。

这很容易做到,但有些用户似乎正在这样做。

这是我的代码:

<form class="forms" action="/checkout" name="ordersubmit" id="shipping" method="post" novalidate="">
    <div class="col-xs-12 col-sm-offset-1 col-sm-11 noPadding">
        <label class="InstructionsBlock" for="Instructions">
            Instructions
        </label>
        <textarea id="Instructions" name="Instructions" maxlength="62" rows="6" cols="50">
        </textarea>
</div>
</form>

    var instructions = $("#Instructions");
    $("form").submit() {
        if (instructions.val(instructions.attr("maxlength")) > 70 || instructions.length) {
        alert("Please limit your instruction to a maximum of 70 characters");
    }
}

表单提交后未通过验证,解决方案可能比我想象的更简单,但我似乎无法完成这项工作。

您应该始终进行服务器端验证。而且我没有看到您的其余代码,所以我不知道 $(this) 是什么。但这是我认为您要检查的内容的一个简单示例。

const $instructions = $("#Instructions");
const max = 70;  // for testing; change to 70 or whatever for yours

// check the attribute is present and less than our max and that the value doesn't exceed it
$("form").on("submit", () => {
  let maxlength = parseInt($instructions.attr("maxlength"));
  if (!$instructions.attr("maxlength") ||
      $instructions.attr("maxlength") > max ||
      $instructions.val().length > maxlength) {
        alert(`Please limit your instruction to a maximum of ${max} characters`); // this should really be in a nice error div or something
        event.preventDefault();
        return false;
      }
   else {
   alert("good");
   return false; // return true for actual submit, or omit this else entirely
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="forms" action="/checkout" name="ordersubmit" id="shipping" method="post" novalidate="">
    <div class="col-xs-12 col-sm-offset-1 col-sm-11 noPadding">
        <label class="InstructionsBlock" for="Instructions">
            Instructions
        </label>
        <textarea id="Instructions" name="Instructions" maxlength="62" rows="6" cols="50">
        </textarea>
     <input type="submit" value="submit" />
</div>
</form>