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

在cshtml中如何实现输入验证,判断输入是否为数字并展示对应提示信息

实现方案

1. 修改DOM结构,新增提示容器

在原有代码基础上增加提示信息的展示位,方便动态切换提示内容:

<div class="form-group">
    <input class="form-control" id="hours" name="hours" type="text" pattern="\d{1,2}" title="NumberOfHoursAlloted" value="@ViewBag.Hours">
    <!-- 新增提示容器,默认隐藏 -->
    <span id="tip" style="display: none; margin: 8px 0; display: block;"></span>
    <input class="btn btn-block" type="submit" onclick="return verifyCheckboxes()" value="Submit" />
</div>

注意这里给onclick事件加了return关键字,避免校验不通过时表单仍自动提交。

2. 编写验证逻辑JS函数

在页面的<script>标签中加入如下逻辑即可:

function verifyCheckboxes() {
    // 获取输入值并去除首尾空格
    const inputValue = document.getElementById('hours').value.trim();
    const tipElement = document.getElementById('tip');
    
    // 校验规则和你原有input上的pattern保持一致:匹配1-2位纯数字
    const numberReg = /^\d{1,2}$/;
    
    if (numberReg.test(inputValue)) {
        // 校验通过
        tipElement.textContent = '添加成功';
        tipElement.style.color = 'green';
        tipElement.style.display = 'block';
        // 需继续提交表单则return true,不需要提交则改为return false
        return true;
    } else {
        // 校验不通过
        tipElement.textContent = '请输入有效数字';
        tipElement.style.color = 'red';
        tipElement.style.display = 'block';
        // 阻止表单提交
        return false;
    }
}

可选优化

如果不需要兼容极低版本浏览器,也可以直接把input的type改为number,配合min、max属性做原生校验,自定义JS校验的优势是可以完全自主控制提示内容、样式和交互逻辑。如果需要支持小数、更大范围的数字,自行修改正则规则即可,比如支持1-2位整数加最多两位小数的正则为/^\d{1,2}(\.\d{1,2})?$/。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 11:24:11