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

ASP.NET MVC中实现输入框失焦时触发HTML5默认表单验证

Hey there! I see you want to trigger that native HTML5 validation popup as soon as the user leaves the mobile number input, instead of waiting for the submit button to be clicked. Let's fix that up for you!

The key here is using HTML5's built-in reportValidity() method — this is what triggers the native validation popup, unlike checkValidity() which only checks validity without showing the message. We'll pair this with the blur event (which fires when the user clicks away from the input) while keeping your existing custom validation message logic.

Modified Script Code

Replace your existing @section Scripts block with this updated version:

@section Scripts {
<script>
function InvalidMsg(textbox) {
    if (textbox.value === '') {
        textbox.setCustomValidity('Please enter mobile number');
    } else if (!textbox.validity.valid) { // Updated to catch all invalid cases (not just type mismatch)
        textbox.setCustomValidity('Please enter valid mobile number');
    } else {
        textbox.setCustomValidity('');
    }
    return true;
}

$(document).ready(function() {
    // Trigger validation when user leaves the mobile input
    $('#Mobile').on('blur', function() {
        // First update the custom validation message
        InvalidMsg(this);
        // Then trigger the native validation popup if input is invalid
        this.reportValidity();
    });

    // Optional: Add the same behavior for first name input if needed
    $('#firstname').on('blur', function() {
        this.reportValidity();
    });
});
</script>
}

What Changed & Why:

  • Updated InvalidMsg function: Swapped textbox.validity.typeMismatch with !textbox.validity.valid to cover all validation failures (empty input, pattern mismatch, etc.) instead of just type-related issues. This ensures your custom message shows up for any invalid state of the mobile input.
  • Blur event listener: Added a handler to the #Mobile input that runs when the user clicks away. It first updates the custom validation message using your existing function, then calls reportValidity() to show the native popup if the input is invalid.
  • Optional first name validation: Included a bonus handler for the first name input so it also triggers validation on blur — just remove this if you don't need it.

This will make the native HTML5 validation popup appear immediately when the user moves from the mobile input to another field, exactly like you wanted!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:33:33