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

JS如何限制变量长度 实现表单字段输入长度超出提示功能

你只需要在firstname非空校验通过的逻辑后新增长度校验规则即可,和你现有空值校验的逻辑风格完全统一。

改动点说明

  • 仅在原有firstname非空校验的if分支内新增了长度判断逻辑,不影响原有其他校验规则的执行顺序
  • 校验触发逻辑和你原有空值校验完全一致,不改动现有交互逻辑
  • 提示内容可根据需求自定义修改为中文

修改后完整代码

$("#register").click(function(e) {
    e.preventDefault();
    var sex = 'male';
    var firstname = '';
    var lastname = '';
    var date = '';
    if ($('.container[data-sex="female"] input:checked').val() == 'on') {
         sex = 'female';
    }
    if ($('#firstname').val() != '' && $('#firstname').val() != null) {
        firstname = $('#firstname').val(); 
        // 新增长度校验逻辑
        if (firstname.length > 20) {
            // 中文提示可替换为:名字长度不能超过20个字符
            return Information('Firstname cannot be longer than 20 characters!');
        }
    }else {
         return Information('Firstname can\'t be empty!');
    }
    if ($('#lastname').val() != '' && $('#lastname').val() != null) {
         lastname = $('#lastname').val(); 
    }else {
          return Information('Lastname can\'t be empty!');
    }
    if ($('#date').val() != '' && $('#date').val() != null) {
         date = $('#date').val(); 
    }else {
          return Information('Date can\'t be empty!');
    }
    $('#core').fadeOut(300);
    $.post('https://lion-register/CreateCharacter', JSON.stringify({
         firstname : firstname,
         lastname : lastname,
         sex : sex,
         date : date,
         queue : MX.CurrentCharacter
    }));
});

如果后续需要给lastname、date等其他输入框加长度校验,也可以用相同的逻辑,在对应非空校验通过后补充长度判断即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:45:06