You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于widget-tweaks在Django表单中限制仅输入字母?

Django表单限制仅输入字母的四次尝试记录

尝试1:自定义Validate函数+内联正则校验(无效)

编写Validate函数并通过onkeypress调用,单独使用内联正则校验也无法生效:

<script type="text/javascript">
    function Validate(e) {
        var keyCode = e.keyCode || e.which;
        var regex = /^[A-Za-z]+$/;
        var isValid = regex.test(String.fromCharCode(keyCode));
        return isValid;
    }
</script>

调用代码:

{% render_field form_built_properties.building_material|attr:"onkeypress(Validate)" class="form-control" %}

单独尝试内联写法同样无效:

{% render_field form_built_properties.building_material|attr:'onkeydown="return /[a-z]/i.test(event.key)"' %}

尝试2:jQuery绑定keydown事件(无效)

使用jQuery绑定keydown事件限制输入,仍无法阻止数字输入:

<script type="text/javascript">
$(document).ready(function() {
$(function () {
  $('#material').keydown(function (e) {
      if (e.shiftKey || e.ctrlKey || e.altKey) {
          e.preventDefault();
      } else {
          var key = e.keyCode;
          if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
              e.preventDefault();
          }
      }
  });
});
});
</script>

对应表单渲染代码:

{% render_field form_built_properties.building_material|attr:'id:"material"' class="form-control" %}

尝试3:forms.py中通过widget添加pattern属性(无效)

在表单类的Meta中为字段widget添加pattern限制,同样无效:

class Meta:
        model = BuiltProperties
        building_material = forms.CharField(required=True, widget=forms.TextInput(
            attrs={'class': 'form-control', 'autocomplete': 'off', 'pattern': '[A-Za-z]+',
                   'title': 'Enter Characters Only '}))
        fields = ['description', 'building_material']

尝试4:widget-tweaks直接添加pattern属性(成功)

使用单行代码成功实现仅输入字母的限制:

{% render_field form_built_properties.building_material|attr:"pattern=[A-Za-z]+"  class="form-control" %}

内容的提问来源于stack exchange,提问作者Alvar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 11:47:41