ASP.Net 核心 app/JS 验证:提示用户更新表单或退出页面
ASP.Net Core app/JS validation: prompt user to update form, or exit page
我有一个 ASP.Net Core/Razor 应用程序,其形式很简单:
<form method="post" id="my_form">
...
</form>
我正在使用内置的客户端验证来处理 <input ...required>
或 <input type="number" min="0" ...>
(Microsoft 在其 MSVS 项目模板中包含 jQuery 验证)。一切正常。
我还在对某些字段进行一些额外的自定义验证。我想让用户选择重新填写表单,或者完全退出表单并重定向到不同的页面:
<script type="text/javascript">
// Form submit
$('#my_form').on('submit', function (e) {
console.log('validateForm...');
//debugger;
// Check basic form validation
let isValid = e.target.checkValidity();
if (!isValid)
return false;
// Validate custom field
let myCustomField = $('#myCustomField').val();
if (myCustomField != 'xyz') {
let response = confirm('MyCustom field is invalid: Update webform?');
if (response) {
return false; // Return to webform
} else {
window.location.href = "./"; // Redirect to app's landing page
}
...
return true;
}
});
</script>
问题:
window.location.href
没有立即重定向我。验证 JS 继续,表单被发布到服务器。
问:我应该改用 location.replace() 之类的东西吗?还是我应该采取完全不同的方法?
回答 Ruikai Feng:不,Ajax 会破坏我正在尝试做的事情的全部目的。我想让用户选择 a) return 到 Web 表单以“更正”它,或者 b) 完全离开表单,并跳转到 DIFFERENT 页面。 Ajax 不会这样做的。
我决定“平底船”,如果发现任何错误,就让我的 JS 验证函数 return 为“false”。这 总是 return 将用户返回到 Web 表单。他们可以“解决”问题,也可以手动浏览到其他页面。
我有一个 ASP.Net Core/Razor 应用程序,其形式很简单:
<form method="post" id="my_form">
...
</form>
我正在使用内置的客户端验证来处理 <input ...required>
或 <input type="number" min="0" ...>
(Microsoft 在其 MSVS 项目模板中包含 jQuery 验证)。一切正常。
我还在对某些字段进行一些额外的自定义验证。我想让用户选择重新填写表单,或者完全退出表单并重定向到不同的页面:
<script type="text/javascript">
// Form submit
$('#my_form').on('submit', function (e) {
console.log('validateForm...');
//debugger;
// Check basic form validation
let isValid = e.target.checkValidity();
if (!isValid)
return false;
// Validate custom field
let myCustomField = $('#myCustomField').val();
if (myCustomField != 'xyz') {
let response = confirm('MyCustom field is invalid: Update webform?');
if (response) {
return false; // Return to webform
} else {
window.location.href = "./"; // Redirect to app's landing page
}
...
return true;
}
});
</script>
问题:
window.location.href
没有立即重定向我。验证 JS 继续,表单被发布到服务器。
问:我应该改用 location.replace() 之类的东西吗?还是我应该采取完全不同的方法?
回答 Ruikai Feng:不,Ajax 会破坏我正在尝试做的事情的全部目的。我想让用户选择 a) return 到 Web 表单以“更正”它,或者 b) 完全离开表单,并跳转到 DIFFERENT 页面。 Ajax 不会这样做的。
我决定“平底船”,如果发现任何错误,就让我的 JS 验证函数 return 为“false”。这 总是 return 将用户返回到 Web 表单。他们可以“解决”问题,也可以手动浏览到其他页面。