簡體   English   中英

表單驗證問題

[英]Form validation problems

我有一個很奇怪的問題。 在表單內部,我隱藏了值為-1的輸入以及用於用戶名的輸入字段。

<form action="" method="POST" name="login" onSubmit="return Validate()">
  <input type="text" id="username"/>
  <input type="hidden" id="available" value="-1"/>
<  input type="submit" value="Send"/>
</form>

在提交功能上,Validate()檢查username輸入的值,該值不能為空,並且Validate()也檢查available輸入的值,該值不能為-1。

function Validate(){

var a=document.getElementById("username").value;
var b=document.getElementById("available").value;

if(a=="" || a==null)
{
    alert("Username cannot be empty");
    return false;
}
else if(b<0)
{
    alert("Form isn't finished");
    return false;
}
else
{
    return true;
}
}

問題在於,只有對一個條件求值,Validate()才能起作用。 如果函數Validate()僅包含1個var(a或b)和1個order(不含if),則它正常工作。 但是,當我這樣說時,Validate使用a和b變量,如果使用if,否則使用條件順序,則它將不起作用。 真的很奇怪..在此先感謝...

在這種情況下,它可以工作:

function Validate(){

var a=document.getElementById("username").value;

if(a=="" || a==null)
{
    alert("Username cannot be empty");
    return false;
}
else
{
    return true;
}
}
<input type="hidden" id="available" value="-1"/>

這里的值是字符串dataType。 鑒於

else if(b<0)  //b is string dataType 

因此失敗了。 因此將其更改為

var b= Number(document.getElementById("available").value);

嘗試使用以下HTML:

<form action="" method="POST" name="login">
    <input type="text" id="username" />
    <input type="hidden" id="available" value="1" />
    <input type="button" value="Send" onClick="return Validate()" />
</form>

JS:

function Validate() {
    var a = document.getElementById("username").value;
    var b = Number(document.getElementById("available").value);
    if (a == "" || a == null) {
        alert("Username cannot be empty");
        return false;
    } else if (b < 0) {
        alert("Form isn't finished");
        return false;
    } else {
        document.login.submit();  //dynamically submit the form
    }
}

如果要獲取每個輸入的錯誤通知,請不要在此處使用if / else,請使用多個if並設置錯誤

function validate(){
   var a=document.getElementById("username").value;
   var b=document.getElementById("available").value;
   var errors = [];

   if(a=="" || a==null){
      errors.push("Invalid username");
   }
   if(b<0 || isNaN(b)){
      errors.push("Invalid available value");
   }
   if(errors.length>0) {
      //do something with errors (like display them
      return false;
   }
}

如果其中一個評估為true,則使用else將跳過其他評估。 例如,如果第一個為空或為null,則它將執行該塊並跳過其他塊。

我正在測試IE和Firefox的代碼,並且可以正常工作。 當您獲得var b的值時,只需添加parseInt即可。

var b= parseInt(document.getElementById("available").value);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM