【问题标题】:Avoid bypassing maxlength attribute using jQuery避免使用 jQuery 绕过 maxlength 属性
【发布时间】:2020-07-08 17:15:10
【问题描述】:

我在尝试验证绕过 textarea 字段中的 maxlength 值的用户时遇到了问题,但我的验证似乎都不起作用。我正在尝试验证用户是否可以将 maxlength 更改为超出我们的初始限制,或者是否从元素中删除了 maxlength。

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

这是我的代码:

<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");
    }
}

提交表单时,它不会验证,解决方案可能比我想象的要容易,但我似乎无法完成这项工作。

【问题讨论】:

  • 我不清楚你想用这个检查什么:if (instructions.val($(this).attr("maxlength")) > 70 || instructions.length)跨度>
  • 我也用 html 编辑了我的代码
  • 我已编辑我的答案以更适用于您的代码

标签: jquery textarea maxlength


【解决方案1】:

您应该始终进行服务器端验证。而且我没有看到你的其余代码,所以我不知道 $(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>

【讨论】:

  • 谢谢。我能够根据您的代码正确设置验证。
猜你喜欢
  • 2011-10-30
  • 2021-05-29
  • 1970-01-01
  • 1970-01-01
  • 2021-04-13
  • 2023-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多