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
InvalidMsgfunction: Swappedtextbox.validity.typeMismatchwith!textbox.validity.validto 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
#Mobileinput that runs when the user clicks away. It first updates the custom validation message using your existing function, then callsreportValidity()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

