字符串需要包含2个单词

Gri*_*zly -1 c# asp.net-mvc-5

我的一个视图上有一个文本框,该文本框不应该接受任何超过2个单词或少于2个单词的内容.这个文本框需要2个单词.

基本上这个文本框接受一个人的名字和姓氏.我不希望人们只输入其中一个.

有没有办法检查space2个单词和另一个字符之间的space字符以及第二个单词后面的任何字符letter,number如果它存在的话?我认为,如果用户意外地'胖手指'在第二个单词之后有一个额外的空格,那应该没问题,但仍然只有2个单词.

例如:

/* the _ character means space */

John               /* not accepted */

John_              /* not accepted */

John_Smith_a       /* not accepted */

John Smith_        /* accepted */
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏.

Rio*_*ams 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
}
Run Code Online (Sandbox Code Playgroud)

使用正则表达式

此外,您可以尝试使用以下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
}
Run Code Online (Sandbox Code Playgroud)

表达式本身可能看起来有点可怕,但可以按如下方式分解:

^        # 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)
Run Code Online (Sandbox Code Playgroud)

"单词"字符\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; }
Run Code Online (Sandbox Code Playgroud)

这将允许您只需调用ModelState.IsValidController Action中的内容,以查看您的Model是否有任何错误:

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