我有一个像这样的Javascript函数:
function validatePath()
{
var path = document.getElementById('server_path').value;
if (path.search(":") == -1)
{
document.getElementById('path_error').innerHTML="Invalid Server Path!";
}
else
{
var host_name = path.split(":")[0]
var regex = new RegExp("^[a-zA-Z0-9.]*$");
if(!(regex.test(host_name)))
{
document.getElementById('path_error').innerHTML="Invalid Server Path!";
}
}
}
如果server_path不正确,则显示错误,但仍然提交表单。我不希望用户能够在server_path正确之前提交表单。我怎么能这样做?
答案 0 :(得分:2)
通常的策略是使用表单的提交处理程序,如果验证失败,则返回false以停止提交:
<form onsubmit="return validatePath();" ...>
然后在函数(伪代码)中:
function validatePath() {
if (validation fails) {
return false;
}
// return any value other than false and the form will submit,
// including undefined
}
答案 1 :(得分:1)
另一种解决方案:
function validatePath() {
var path = document.getElementById('server_path').value;
var submitButton = document.getElementById('submit');
document.getElementById('path_error').innerHTML='';
submitButton.removeAttribute('disabled');
if (path.search(":") == -1){
document.getElementById('path_error').innerHTML="Invalid Server Path!";
submitButton.setAttribute('disabled', 'disabled');
}
else{
var host_name = path.split(":")[0]
var regex = new RegExp("^[a-zA-Z0-9.]*$");
if(!(regex.test(host_name))){
document.getElementById('path_error').innerHTML="Invalid Server Path!";
submitButton.setAttribute('disabled', 'disabled');
}
}
}
答案 2 :(得分:0)
您可以禁用提交按钮,直到路径正确为止。喜欢这个
<input type='submit' disabled='true' onclick='return validatePath()' id='submit'/>
我在你的javascript代码中做了一些更改。
function validatePath() {
var path = document.getElementById('server_path').value;
if (path.search(":") == -1){
document.getElementById('path_error').innerHTML="Invalid Server Path!";
}
else{
var host_name = path.split(":")[0]
var regex = new RegExp("^[a-zA-Z0-9.]*$");
if(!(regex.test(host_name))){
document.getElementById('path_error').innerHTML="Invalid Server Path!";
}
else {
document.getElementById('submit').disabled=false;
}
}
}