Dotnet Core MVC中邮箱重复报错时限制跳转至下一个输入框
问题场景
- 数据库中已预先存储
test@123.com邮箱 - 当新用户输入该邮箱时,后端代码会抛出
Email already exists in the database.的错误 - 需求:报错时,禁止用户跳转到下一个输入框(Mobile输入框)
现有后端校验代码
public void AddStudent(Student student) { using (SqlConnection con = new SqlConnection(connectionString)) { SqlCommand cmdCheckEmail = new SqlCommand("SELECT COUNT(*) FROM Student WHERE Email = @Email", con); cmdCheckEmail.Parameters.AddWithValue("@Email", student.Email); SqlCommand cmdAddStudent = new SqlCommand("spAddStudent", con); cmdAddStudent.CommandType = CommandType.StoredProcedure; cmdAddStudent.Parameters.AddWithValue("@FirstName", student.FirstName); cmdAddStudent.Parameters.AddWithValue("@LastName", student.LastName); cmdAddStudent.Parameters.AddWithValue("@Email", student.Email); cmdAddStudent.Parameters.AddWithValue("@Mobile", student.Mobile); cmdAddStudent.Parameters.AddWithValue("@Address", student.Address); con.Open(); int emailCount = (int)cmdCheckEmail.ExecuteScalar(); if (emailCount > 0) { throw new Exception("Email already exists in the database."); } cmdAddStudent.ExecuteNonQuery(); con.Close(); } }
实现方案
要阻止报错时跳转到Mobile输入框,需要在前端配合做校验和拦截:
1. 实时校验+输入框禁用
在Email输入框失去焦点或输入内容时,调用后端接口提前校验邮箱状态,一旦发现重复,禁用Mobile输入框并强制保留焦点在Email输入框:
// JavaScript示例(jQuery) $('#emailInput').on('blur', async function() { const email = $(this).val().trim(); if (!email) return; const response = await fetch('/api/CheckEmailExists', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email }) }); const { exists } = await response.json(); if (exists) { $('#emailError').text('邮箱已存在').show(); // 禁用Mobile输入框 $('#mobileInput').prop('disabled', true); // 强制焦点返回Email输入框 $('#mobileInput').on('focus', () => $('#emailInput').focus()); } else { $('#emailError').hide(); $('#mobileInput').prop('disabled', false); $('#mobileInput').off('focus'); } });
2. 表单提交后的错误拦截
如果用户直接提交表单触发后端报错,前端捕获错误后将焦点放回Email输入框:
$('#studentForm').on('submit', async function(e) { e.preventDefault(); const formData = new FormData(this); try { const response = await fetch('/api/AddStudent', { method: 'POST', body: formData }); if (!response.ok) { const errorMsg = await response.text(); if (errorMsg.includes('Email already exists')) { $('#emailError').text('邮箱已存在').show(); $('#emailInput').focus(); $('#mobileInput').prop('disabled', true); return; } throw new Error(errorMsg); } // 提交成功后的逻辑 window.location.href = '/student-list'; } catch (err) { console.error('提交失败:', err); } });
后端配套调整
新增一个用于实时校验的接口,复用现有邮箱查询逻辑:
[HttpPost] public IActionResult CheckEmailExists([FromBody] string email) { using (SqlConnection con = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM Student WHERE Email = @Email", con); cmd.Parameters.AddWithValue("@Email", email); con.Open(); int count = (int)cmd.ExecuteScalar(); return Json(new { exists = count > 0 }); } }
额外提示
- 禁用输入框比单纯阻止焦点跳转更直观,用户能清晰感知当前状态
- 若使用ASP.NET WebForms,可以在后台捕获异常后,通过
EmailTextBox.Focus()回归焦点,并设置MobileTextBox.Enabled = false
内容的提问来源于stack exchange,提问作者Sudharshan S
相关产品推荐
相关产品推荐

