2015-05-26 76 views
3

我有一個輸入驗證數組。 數組的每一行表示單個輸入驗證;正則表達式檢查和一串一串來顯示的情況下,驗證壞了的用戶:用戶輸入驗證通過在WPF文本框的reg exp

public class myClass 
{ 
    public static string[][] inputsInfo = new string[4][]; 

    static myClass() 
    { 
    // ID - 9 digits 
    inputsInfo[0] = new string[2] { "^[0-9]{9}$", "exactly 9 digits (0-9)" }; 

    // only letters and possibly more than one word 
    inputsInfo[1] = new string[2] { "^[A-Za-z]{2,}(()[A-Za-z]{2,})*$", "only letters (A-Z) or (a-z)" }; 

    // Number - unlimited digits 
    inputsInfo[2] = new string[2] { "^[0-9]+$", "only digits (0-9)" }; 

    // username, password 
    inputsInfo[3] = new string[2] { "^[A-Za-z0-9]{6,}$", "at least 6 characters.\nOnly letters (A-Z) or (a-z) and digits (0-9) are allowed" }; 

    } 
.............. 
.............. 
} 

我有包含WPF文本框的窗戶。有一些字段具有相同的輸入驗證,這就是爲什麼我要將所有輸入驗證保存在數組中,所以我可以選擇當前需要的驗證。

我有這樣的形式:

............... 

     <TextBlock Grid.Row="2" Grid.Column="0" Text="First name"/> 
     <TextBox x:Name="firstName" Grid.Row="2" Grid.Column="1"/> 
     <Button Grid.Row="2" Grid.Column="2" Content="Search"/> 

     <TextBlock Grid.Row="3" Grid.Column="0" Text="Last name"/> 
     <TextBox x:Name="lastName" Grid.Row="3" Grid.Column="1"/> 
     <Button Grid.Row="3" Grid.Column="2" Content="Search"/> 

     <TextBlock Grid.Row="4" Grid.Column="0" Text="ID number"/> 
     <TextBox x:Name="ID" Grid.Row="4" Grid.Column="1"/> 
     <Button Grid.Row="4" Grid.Column="2" Content="Search"/> 

............... 

每個文本框有一個Click事件近按鈕。 如何通過點擊按鈕執行輸入驗證?

有沒有辦法通過XAML代碼做到這一點? 或僅在代碼隱藏的C#代碼?

任何幫助將不勝感激。

+0

有人有解決方案嗎? –

回答

0

如何通過按鈕單擊執行輸入驗證?

爲什麼不在監視目標文本框的綁定文本屬性進行驗證的ViewModel上創建布爾標誌。實施例

VM:

public string FirstName { get { return _firstName; } 
          set { _firstname = value; 
           PropertyChanged("IsFirstNameValid"); 
           PropertyChanged("FirstName"); 
           } 
         } 

public bool IsFirstNameValid { get { return Regex.IsMatch(FirstName, 
                  ValidationPatternFirstName); }} 

XAML

<TextBox x:Name="firstName" 
     Text={Binding FirstName, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" /> 

然後在任何改變所存儲的值FirstName布爾值IsFirstNameValid將準確地反映狀態時以後訪問。

此外,您可以綁定到屏幕上的IsFirstNameValid以顯示圖標或不顯示圖標,它將根據其狀態進行更新。