RegularExpressionValidator not firing on white-space entry

前端 未结 5 1360
说谎
说谎 2020-12-07 01:54

I want to validate string containing only numbers. Easy validation? I added RegularExpressionValidator, with ValidationExpression=\"/d+\".

Looks okay - but nothing

5条回答
  •  天命终不由人
    2020-12-07 02:30

    This is by design and tends to throw many people off. The RegularExpressionValidator does not make a field mandatory and allows it to be blank and accepts whitespaces. The \d+ format is correct. Even using ^\d+$ will result in the same problem of allowing whitespace. The only way to force this to disallow whitespace is to also include a RequiredFieldValidator to operate on the same control.

    This is per the RegularExpressionValidator documentation, which states:

    Validation succeeds if the input control is empty. If a value is required for the associated input control, use a RequiredFieldValidator control in addition to the RegularExpressionValidator control.

    A regular expression check of the field in the code-behind would work as expected; this is only an issue with the RegularExpressionValidator. So you could conceivably use a CustomValidator instead and say args.IsValid = Regex.IsMatch(txtInput.Text, @"^\d+$") and if it contained whitespace then it would return false. But if that's the case why not just use the RequiredFieldValidator per the documentation and avoid writing custom code? Also a CustomValidator means a mandatory postback (unless you specify a client validation script with equivalent javascript regex).

提交回复
热议问题