Search code examples
asp.netregexext.net

Ext.net C# testfiled regex validation


Working on Ext.net project. I need to set a validation on password field for not allowing blank spaces before the password or after password and also the length of the password should not be more than 15 characters including blank spaces. I have done following so far but does not work.

The issue is it counts space between text as invalid. E.g. It does not allow "Pass word", what I want to not allow " password" or "password ".

<ext:TextField ID="txtConfirmPwd" AllowBlank="false" InputType="Password" Name="txtConfirmPwd" runat="server" StyleSpec="width:96%;" Regex="^[^\s.^\s]{1,15}$" InvalidClass="invalidClass" Validator="ComparePwd" IDMode="Static">
<Listeners>
    <Valid Handler="InvalidClass(this,true);" />
    <Invalid Handler="InvalidClass(this,false);" />
</Listeners>
</ext:TextField>

Solution

  • You may use

    Regex="^\S(?:.{0,13}\S)?$"
    

    Details:

    • ^ - start of string
    • \S - a nonwhitespace
    • (?:.{0,13}\S)? - 1 or 0 sequences of:
      • .{0,13} - any zero to thirteen chars
      • \S - a nonwhitespace symbol
    • $ - end of string.

    This means, the first char must be a char other than whitespace and then there can be any up to 14 chars with the last one being a nonwhitespace.

    You may actually use lookaheads to achieve the same, ^(?!\s)(?!.*\s$).{1,15}$. The (?!\s) is a negative lookahead that fails the match if the first (as the pattern is immediately following ^) char is a whitespace char and (?!.*\s$) fails the match if the whitespace appears right at the end of the string. However, it is unnecessarily complex for the current task.