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

ASP.NET Core MVC中使用jQuery validation实现日期与年龄校验

实现方案

1. 出生日期自动计算年龄+基础规则校验

首先需要给jQuery validation新增自定义校验规则,实现「出生日期不能为当日、至少是5年前日期」的要求,再绑定出生日期字段的变更事件,选择日期后自动计算年龄填入年龄字段。

// 新增出生日期自定义校验规则
$.validator.addMethod("minAgeDate", function(value, element, params) {
    if (!this.optional(element)) {
        const birthDate = new Date(value);
        const today = new Date();
        // 清除时分秒避免当日时间计算误差
        today.setHours(0,0,0,0);
        // 计算n年前的最小允许日期
        const minAllowDate = new Date(today.getFullYear() - params, today.getMonth(), today.getDate());
        // 校验逻辑:出生日期早于今日,且早于等于最小允许日期
        return birthDate < today && birthDate <= minAllowDate;
    }
    return true;
}, $.validator.format("出生日期需至少为{0}年前的日期,且不能为当日"));

// 公用年龄计算方法
function calculateAge(birthDateStr) {
    const birthDate = new Date(birthDateStr);
    const today = new Date();
    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();
    // 未到当年生日则年龄减1
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}

// 绑定出生日期变更事件,自动计算年龄
$('#txtFecNac').on('change', function() {
    if ($(this).valid()) {
        const age = calculateAge($(this).val());
        $('#txtEdad').val(age).valid(); // 赋值后自动触发年龄字段校验
    } else {
        $('#txtEdad').val('');
    }
});

2. 监护人字段动态校验

通过jQuery validation的depends属性实现字段的动态必填规则,年龄≤5时要求填写representative字段,否则该字段不做强制要求。完整表单校验配置如下:

$(document).ready(function() {
    $('#formPaciente').validate({
        rules: {
            txtFecNac: {
                required: true,
                minAgeDate: 5 // 传入最小年龄要求参数
            },
            txtEdad: {
                required: true,
                range: [5,90] // 注意规则名大小写敏感,需小写range才会生效
            },
            representative: {
                required: {
                    depends: function() {
                        // 年龄≤5时该字段必填
                        return parseInt($('#txtEdad').val() || 0) <= 5;
                    }
                }
            }
        },
        messages: {
            txtFecNac: {
                required: "出生日期为必填项",
                minAgeDate: "出生日期需至少为5年前的日期,且不能为当日"
            },
            txtEdad: {
                required: "年龄为必填项",
                range: "年龄需在5到90岁之间"
            },
            representative: {
                required: "未满6周岁需填写监护人信息"
            }
        }
    });
});

补充说明

  • 前端校验仅用于提升用户体验,后端必须同步实现相同校验逻辑,避免前端校验被恶意绕过
  • 如果你需要结合ASP.NET Core MVC数据注解实现前后端校验统一,可以自定义MinAgeAttribute继承ValidationAttribute并实现IClientModelValidator接口,框架会自动生成前端校验规则,无需手动编写jQuery校验代码

预期效果参考:
效果示例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:57:04