2013-05-27 22 views
0

我在我的asp.net MVC 3次一個使用這種期望的結果:簡單jQuery驗證是不是給

<script language="javascript" type="text/javascript"> 
    $(document).ready(function() { 
     $('.YesNoNotApplicable').change(function() { 
      if ($(this).val() === '2') { 
       $(this).closest('td').next('td').find('input').show(); 
      } 
      else { 
       $(this).closest('td').next('td').find('input').hide(); 
      } 
     }); 
     $('#submitDocument').click(function() { 
      if ($(".checkString16").val().length > 16) { 
       alert("The text can be up to 16 symbols"); 
       return false; 
      } 
      else if (!$.isNumeric($(".checkULong").val())) { 
       alert("Insert integer"); 
       return false; 
      } 
      else if (!$(".checkFloat").val().match('^[0-9]*\.[0-9]*$')) { 
       alert("Insert float"); 
       return false; 
      } 
      return true; 
     }); 
    }); 
</script> 

這裏的問題是,我變得非常隨機的結果。如果我的整數檢查沒有像現在那樣註釋,我會一直得到整數警報。如果我對它進行評論,那麼有時候浮動檢查有時會起作用,有時候現在,如果它第一次起作用,那麼即使我將值更改爲浮動值,我也會不斷得到錯誤。

+1

你可以在JSFiddle.net上顯示你的問題演示嗎?或在jsbin.com上? –

+0

呃,讓我試試,我需要學會使用這個。 – Leron

+0

好吧,它似乎有太多刪除.. – Leron

回答

1

我打算向你推薦另一種檢查javascript中數字類型的方法。

首先建立數學函數命名空間像下面這樣:

mathFunctions = {}; 

通過使用命名空間(實際上JS對象)使代碼更有條理。

然後,你需要創建一些方法,將執行由程序所需要的驗證檢查:

mathFunctions.isInt = function(value) { 
    return typeof value === 'number' && value % 1 == 0; 
} 

mathFunctions.isFloat = function(value) { 
    return typeof value === 'number' 
     && parseFloat(value) == parseInt(value, 10) && !isNaN(value); 
} 

所以每當你需要檢查一個數學值,調用這些方法,你會得到適當的結果。看看下面的驗證碼,例如:

try { 
    if ($(".checkString16").val().length > 16) { 
     throw "The text can be up to 16 symbols"; 
    } else if (!mathFunctions.isInt($(".checkULong").val())) { 
     throw "Insert integer"; 
    } else if (!mathFunctions.isFloat($(".checkFloat").val())) { 
     throw "Insert float"; 
    } 
    validationResult = true; 
} catch(exc) { 
    alert(exc) 
    validationResult = false; 
} 
return validationResult; 

你可以找到更多的方法實現對這個職位:How do I check that a number is float or integer?

編輯

可以在http://api.jquery.com/jQuery.isNumeric/此頁面$看到。 isNumeric()即使在float值時也返回TRUE。