PostSharp Parameter Validation - Using RegularExpressionAttribute to find leading/trailing spaces

社会主义新天地 提交于 2019-12-13 18:32:10

问题


I'm using PostSharp 3.1 to validate parameters of properties using validation attributes. I would like to use RegularExpressionAttribute to perform the validation, which takes in a string representing the regex. I would like to throw an exception if the string has any leading or trailing whitespace, but the string may contain spaces between words.

Prior to using PostSharp attributes, I performed a check like this:

if(name == name.Trim())
{
    throw new ArgumentException("name", "Name contains leading/trailing whitespace");
}

Instead, I want something like this:

[RegularExpression("[ \\s]+|[ \\s]+$")]
public name { get; private set; }

Which matches (i.e. these are illegal and throw exceptions)

"  North West"
"North West  "
"  North West  "
"  NorthWest"
"NorthWest  "
"  NorthWest  "

But does NOT match (i.e. these are legal)

"North West"
"NorthWest"

Unfortunately it seems my regex matches the wrong way around and I am given to understand there is no "not" operator in regex. Also, my current expression matches (and throws exception) on the valid string "North West" as it matches the space in the middle.

Is it possible and neat to do this without creating a custom attribute?


回答1:


The regex inside RegularExpressionAttribute must match the whole text. Here is an excerpt from the source code:

override bool IsValid(object value) {
 //...
 // We are looking for an exact match, not just a search hit. This matches what
 // the RegularExpressionValidator control does
 return (m.Success && m.Index == 0 && m.Length == stringValue.Length);

So, you need to add .* to capture anything that is in-between.

You can use

^[^ ].*[^ ]$

The regex means "match a non-space, then any number of characters other than whitespace, and non-space at the end". It also means there must be at least 2 characters to match. Here is a demo where you can test this regex. Though it is for PCRE, the pattern will behave the same in C# environment (just I added m flag for demonstration purposes).

In order to just perform the check and allow even 1 or 0 character string, you can use look-arounds ^(?=[^ ]).*(?<=[^ ])$. See another demo and pay attention to the last line where 1 is now considered a valid input.



来源:https://stackoverflow.com/questions/30483044/postsharp-parameter-validation-using-regularexpressionattribute-to-find-leadin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!