Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Javascript中正确验证两个或多个字段?_Javascript_Validation - Fatal编程技术网

如何在Javascript中正确验证两个或多个字段?

如何在Javascript中正确验证两个或多个字段?,javascript,validation,Javascript,Validation,我想使用JavaScript代码一起验证两个字段。 我所做的是在用户输入无效数据时禁用提交按钮 大概是这样的: 问题是,当我在字段1中输入无效数据时,按钮被禁用,但当我在第二个字段中添加正确的表单数据时,按钮再次被启用,我甚至使用了全局变量,但问题仍然存在 我的JavaScript代码是: <script> var sw=0; function valqid(qid){ if(isNaN(qid) || parseInt(qid)<0){ alert("Please

我想使用JavaScript代码一起验证两个字段。 我所做的是在用户输入无效数据时禁用提交按钮

大概是这样的:

问题是,当我在字段1中输入无效数据时,按钮被禁用,但当我在第二个字段中添加正确的表单数据时,按钮再次被启用,我甚至使用了全局变量,但问题仍然存在

我的JavaScript代码是:

<script>
var sw=0;
function valqid(qid){

 if(isNaN(qid) || parseInt(qid)<0){
  alert("Please Enter Valid Question ID!");
  document.getElementById("button").disabled = true;
  window.sw=1; 
 }
 else{
  if(window.sw==0){
  document.getElementById("button").disabled = false;
 }
 }


}

function valans(ans){

 if(parseInt(ans)!=0 && parseInt(ans)!=1){
  alert("Please Enter Valid Answer!");
  document.getElementById("button").disabled = true;
  window.sw=1; 
 }
 else{
  if(window.sw==0){
  document.getElementById("button").disabled = false;
 }
 }


}
</script>

var-sw=0;
函数valqid(qid){

如果(isNaN(qid)| parseInt(qid)您可以使用这种简单的方法

<script>
function valqid(qid){
 if(isNaN(qid) || parseInt(qid)<0){
  alert("Please Enter Valid Question ID!");
  document.getElementById("button").disabled = true;
 }
 else if(parseInt(ans)!=0 && parseInt(ans)!=1){
  alert("Please Enter Valid Answer!");
  document.getElementById("button").disabled = true;
  }
 else{
     document.getElementById("button").disabled = false;
  }
 }
</script>

函数valqid(qid){

if(isNaN(qid)| parseInt(qid)为什么要生成2个函数而不是1个函数?因为当用户输入值时,函数的输入值就出现了。如果您愿意,我可以上传整个html文件?假设表单可以同时包含这两个值,您可以将它们传递到单个函数中,并检查其中一个是否为空(并禁用按钮),然后检查是否有有效值。类似于:
if(x==null | | y==null){disableButton();}else if(isValid(x)&&isValid(y)){enableButton();}else{disableButton();}
请让我上传整个代码。但是除非调用valans函数,否则ans变量将没有任何值。在这种情况下,您只需调用valqid();在第二种方法的末尾,它将检查第一种方法的状态,第一种方法是否使按钮处于启用或禁用状态。现在,请建议对我的整个代码进行更改。
<script>
function valqid(qid){
 if(isNaN(qid) || parseInt(qid)<0){
  alert("Please Enter Valid Question ID!");
  document.getElementById("button").disabled = true;
 }
 else if(parseInt(ans)!=0 && parseInt(ans)!=1){
  alert("Please Enter Valid Answer!");
  document.getElementById("button").disabled = true;
  }
 else{
     document.getElementById("button").disabled = false;
  }
 }
</script>