2009-08-03 12 views
0

你好,我想驗證輸入,所以算話的方法如下:驗證兩個以上的單詞作爲最小的基於ASP:文本框

public static string validateisMoreThanOneWord(string input, int numberWords) 
     { 
      try 
      { 
       int words = numberWords; 
       for (int i = 0; i < input.Trim().Length; i++) 
       { 
        if (input[i] == ' ') 
        { 
         words--; 
        } 
        if (words == 0) 
        { 
         return input.Substring(0, i); 
        } 
       } 
      } 
      catch (Exception) { } 
      return string.Empty; 
     } 

當我把這個方法,因此該方法返回時驗證後爲空,頁面不會回發(如AjaxToolKit上的RequireFieldValidator)

謝謝!

回答

1

首先,你可以簡化很多:

public static bool validateIsMoreThanOneWord(string input, int numberWords) 
{ 
    if (string.IsNullOrEmpty(input)) return false; 

    return (input.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Length >= numberWords);  
} 

此版本還具有易於擴展到包括其他空白狀突片或回車的優勢。

下一步是您不能停止頁面單獨回發服務器端代碼。相反,您需要使用CustomValidator併爲其ClientValidationFunction寫一些javascript,它看起來像這樣:

var numberWords = 2; 
function checkWordCount(source, args) 
{   
    var words = args.Value.split(' '); 
    var count = 0; 
    for (int i = 0; i<words.length && count<numberWords;i++) 
    { 
     if (words[i].length > 0) count++; 
    } 
    args.IsValid = (count >= numberWords); 
    return args.IsValid; 
} 
3

將其實施爲custom validator。例如,請參閱http://aspnet.4guysfromrolla.com/articles/073102-1.aspx

如果您不想在沒有回發的情況下工作,則還應該在Javascript中實施客戶端版本的驗證。你可以可以有客戶端版本使C#實現AJAX調用,但它是相當簡單的邏輯 - 所以我會選擇在Javascript中實現它,並保存用戶一個AJAX請求。

相關問題