2016-04-21 82 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; } 
} 
相关问题