Search code examples
c#asp.netregextextbox

RegularExpressionValidator.ValidationExpression text should startwith


I have write on aspx.cs side this code. I want to validate the textbox with this rule, text should start with XYZ. But it doesn't work. When i try "XYZjhsdfk", validator returns the error message of the RegularExpressionValidator. But it should pass, because "XYZjhsdfk" starts with "XYZ".

RegularExpressionValidator.ValidationExpression = @"^" + "XYZ";

I have tried many things and searched on google but i can not make it work like i want.

I have also tried these:

RegularExpressionValidator.ValidationExpression = @"^" + "XYZ" + ".";
RegularExpressionValidator.ValidationExpression = @"^" + "XYZ" + "*";

Solution

  • The regex used in RegularExpressionValidator should match the whole string.

    You may add .* after ^XYZ to match that part:

    RegularExpressionValidator.ValidationExpression = @"^XYZ.*";
    

    Details

    • ^ - start of a string
    • XYZ - some literal value
    • .* - one or more chars other than a newline (replace with [\s\S]* to match any chars, but this would be only good if the input could contain newlines, which is probably not the case here).