premium_mesg_dev
premium_mesg_dev

Reputation: 158

RegularExpressionValidator not firing on white-space entry

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

Looks okay - but nothing validated when only space is entered! Even many spaces are validated okay. I don't need this to be mandatory.

I can trim on server, but cannot regular expression do everything!

Upvotes: 6

Views: 10104

Answers (5)

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

try to use Ajax FilteredTextbox, this will not allow space....... http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/FilteredTextBox/FilteredTextBox.aspx

Upvotes: 1

Ahmad Mageed
Ahmad Mageed

Reputation: 96497

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).

Upvotes: 12

Kelsey
Kelsey

Reputation: 47726

The RegularExpressionValidator is a nice wrapper for doing regex checks but it will not validate against an empty control. You could use a CustomValidator and then do the regular expression check in a javascript function that you attach to the validator.

It will validate against an empty (blank) control as long as you set the ValidateEmptyText property to true.

You can read more about the CustomValidators on MSDN here.

Upvotes: 1

Roger Willcocks
Roger Willcocks

Reputation: 1669

Try using ^\d+$ to force the digits to fill the entire line. ^ = line start $ = line end

Upvotes: 0

Scanningcrew
Scanningcrew

Reputation: 790

Your question is a little hard to follow, but if you are asking how to write a regular expresion which only accepts digits I think your mistake is in using forward-slash instead of backslash. Try

"\d+"

Upvotes: 1

Related Questions