2016-04-21 138 views
-1

我在我的一個視圖上有一個文本框,並且該文本框不應該接受超過2個單詞或少於2個單詞的任何內容。這個文本框需要2個單詞。字符串需要包含2個字

基本上這個文本框接受一個人的名字和姓氏。我不希望人們只輸入一個或另一個。

有沒有一種方法來檢查和2個字之間的space字符與任何letternumber,如果它存在等第二個字後,沿另一space性格嗎?我認爲,如果用戶在第二個單詞之後偶然「胖手指」多出一個空格,那應該很好,但仍然只有2個單詞。

例如:

/* the _ character means space */ 

John    /* not accepted */ 

John_    /* not accepted */ 

John_Smith_a  /* not accepted */ 

John Smith_  /* accepted */ 

任何幫助理解。

回答

5

有,你可以用它來解決這個多種方法,我將回顧在幾個。

使用String.Split()方法

你可以使用String.Split()方法打破了一個字符串轉換成它的帶分隔符的各個組件。在這種情況下,你可以使用空格作爲分隔符來獲得個人的話:

// Get your words, removing any empty entries along the way 
var words = YourTextBox.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); 

// Determine how many words you have here 
if(words.Length != 2) 
{ 
    // Tell the user they made a horrible mistake not typing two words here 
} 

使用正則表達式

此外,你可以嘗試使用Regex.IsMatch()通過正則表達式來解決這個方法:

// Check for exactly two words (and allow for beginning and trailing spaces) 
if(!Regex.IsMatch(input,@"^(\s+)?\w+\s+\w+(\s+)?")) 
{ 
    // There are not two words, do something 
} 

表達本身可能看起來有點嚇人,但它可以被分解如下:

^  # This matches the start of your string 
(\s+)? # This optionally allows for a single series of one or more whitespace characters 
\w+  # This allows for one or more "word" characters that make up your first word 
\s+  # Again you allow for a series of whitespace characters, you can drop the + if you just want one 
\w+  # Here's your second word, nothing new here 
(\s+)? # Finally allow for some trailing spaces (up to you if you want them) 

「單詞」字符\w是正則表達式中的一個特殊字符,它可以表示數字,字母或下劃線,相當於[a-zA-Z0-9_]

使用MVC的RegularExpressionAttribute

最後以正則表達式的優勢,因爲你正在使用MVC,你可能對你的模型本身的優勢[RegularExpressionValidation]屬性:

[RegularExpression(@"^(\s+)?\w+\s+\w+(\s+)?", ErrorMessage = "Exactly two words are required.")] 
public string YourProperty { get; set; } 

這將允許你只需在您的控制器操作中調用ModelState.IsValid以查看您的型號是否有任何錯誤:

// This will check your validation attributes like the one mentioned above 
if(!ModelState.IsValid) 
{ 
    // You probably have some errors, like not exactly two words 
} 
+0

什麼關於匹配「Cpl \ 3 John Smith」或「Mr.約翰史密斯?我有'@「^(\ s +)?[A-Za-z _.-] + \ s \ w + \ s \ w +(\ s +)?$」' –

+0

您是否希望允許那些除了以前的案例或作爲一個完全獨立的集?從技術上講,這些由三個詞組成。 –

+0

是的,除了我之前的情況。 3是最大值和最小值 –

2

使用這樣

string s="John_Smith_a" 
if (s.Trim().Split(new char[] { ' ' }).Length > 1) 
{ 
} 
0

最簡潔的方法是使用正則表達式IsMatch方法是這樣的:

Regex.IsMatch("One Two", @"^\w+\s\w+\s?$") 

返回true如果輸入匹配。

0
Match m = Regex.Match(this.yourTextBox.Text, @"[^\w\s\w$]", String.Empty); 
if (m.Success) 
    //do something 
else 
    //do something else 

由於我對正則表達式的知識非常有限,我相信這會解決您的問題。

0

試試這個

if (str.Split(' ').Length == 2) 
{ 
    //Do Something 
} 

str是變量牽着你要比較的字符串

1

標籤意味着MVC在這裏,所以我會建議使用RegularExpressionAttribute類:

public class YourModel 
{ 
    [RegularExpression(@"[^\w\s\w$]", ErrorMessage = "You must have exactly two words separated by a space.")] 
    public string YourProperty { get; set; } 
}