RegularExpressionValidator not firing on white-space entry - c#

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!

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

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+"

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.

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

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

Related

textbox prevent some keys

I don´t know how to resolve a situation i have. I have a regular expression that validate a textbox input, what i need is to prevent or remove characters that not mach the regular expresion while the user is typing.
my regular expression is:
^[A-Z0-9]+(\.[A-Z0-9]+|[A-Z0-9]*)*$.
it allows letters,numbers, and dots (but no more than one consecutive), but it can be change without notificacion (by system configuration)
Any idea how to solve it?
Upd: it`s a winforms application
You could keep a local variable that stores the value of the textbox. On each keypress, check whether the key matches the regex. If so, add the character to the local variable, and set the textbox's text field to the variable. Otherwise set the textbox to the current value of the local variable, thus overwriting the bad input.
Use Custom validator with this regex.

Optimistic RegEx Matching for User Text Entry

I'm working on a text entry application that uses regular expressions to validate user input. The goal is to allow keypresses that fit a certain RegEx while rejecting invalid characters. One issue I've run into is that when a user starts inputting information they may create a string that doesn't yet match the given regex, but could cause a match in the future. These strings get erroneously rejected. Here's an example - given the following regex for inputting date information:
(0?[1-9]|10|11|12)/(0?[1-9]|[12]\\d|30|31)/\\d{2}\\d{2}
A user may begin entering "1/" which could be a valid date, but RegEx.IsMatch() will return false and my code ends up rejecting the string. Is there a way to "optimistically" test strings against a regular expression so that possible or partial matches are allowed?
Bonus: For this RegEx in particular there are some sequences which cause required characters. For example, if the user types "2/15" the only possible valid character they could enter next is "/". Is it possible to detect those scenarios so that the required characters could be automatically entered for the user to ease input?
What you can do is anchor your RegExp (i.e. adding ^ and $, as in start/end of line) and make some component optionnal for validation, but strictly defined if present.
Something looking like this:
^(0?[1-9]|10|11|12)(/((0?[1-9]|[12]\\d|30|31)(/(\\d{2}(\\d{2})?)?)?)?)?$
I do realize it looks horrible but as far as I know there is no way to tell the regexp engine to validate as long as the string satisfies the beginning of the regexp pattern.
In my opinion, the best way to achieve what you want to do is to create separate inputs for day/month/date and check their value when leaving the text field.
It also provides a better visibility and user-experience, as I believe no one likes to be prevented from typing certain characters into a text field with or without noticing them disappear as they type or having slashes inserted automatically and without notice.
Have you ever used and app or form that worked that way, simply refusing to accept any keypress it didn't like? If the answer is Yes, did it blow an electronic raspberry each time you pressed a wrong key?
If you really need to validate the input before the form is submitted, use a passive feedback mechanism like a red border around the textfield that disappears the regex matches the input. Also, make sure there's a Help button or a tooltip nearby to provide constructive feedback.
Of course, the best option would be to use a dedicated control like a date-entry widget. But whatever you do, don't do it in such a a way that it feels like you're playing guessing games with the user.

When's an Apostrophe not an Apostrophe - validation .Net / Javascript

I have an regular expression validator for emails in .NET 2.0 which uses client side validation (javascript).
The current expression is "\w+([-+.']\w+)#\w+([-.]\w+).\w+([-.]\w+)" which works for my needs (or so I thought).
However I was getting a problem with apostrophes as I had copy/pasted an email address from Outlook into the forms text field
Chris.O’Brian#somerandomdomain.com
You can see the apostrophe is a different character from what get if I were just to type into a text box
' vs ’ - but both are apostrophes
Okay I thought , lets just add in this character into the validation string so I get
"\w+([-+.'’]\w+)#\w+([-.]\w+).\w+([-.]\w+)"
I copy paste the "special" apostrophe into the validation expression, then I type the email and use the same clipboard item to paste the apostrophe but the validation still fails.
The apostrophe doesn't look the same in the .net code behind file as the .net form and because the validation is still failing , I am presuming it's being considered a different character because of some sort of encoding of the .cs source file?
Does this sound plausible, has someone else encountered the same problem?
Thanks
You should add a '+' after ([-+.'`]\w+), to allow for multiple groups of 'words'. The expression you gave only allows for two words, and you have three: Chris, O, Brian.
Hope this makes things clearer.
There will be a tendency in something like Outlook to use 'Smart Quotes'
Here's some background information
If you just pasted the ’ (U+2019 RIGHT SINGLE QUOTATION MARK) into your document and it didn't work it means that your document does not use unicode.
When you encode and send the file as UTF-8 (for example) it works just fine without further modifications. Otherwise you have to escape it via \u2019 which also works in JavaScript's regular expressions:
"\w+([-+.'\u2019]\w+)#\w+([-.]\w+).\w+([-.]\w+)"
In XML you could test the value of an apostrophe character by evaluating it against its character entity reference:
'
That entity does not exist in the SGML form of HTML, however. And as an added bonus JavaScript cannot compare a single quote to a double quote. When compared they evaluated to true. The only solution there is to convert single quote and double quote characters to a character entity reference of your invention, perform the comparison, and then replace those invented entity references with the proper quote characters.

c# Use two validators on the same field

I have run into a problem trying to modify a form I myself have not built.
The form has a asp:input field for a date value, wich is checked by a requiredFieldVal and a rangeVal. The rangeVal has type set to "date" and min value 2000-01-01: max value 3000-01-01
Now to the problem, I'm trying to add so that the user also can input the date in the form of "20000101" in other words without the "-".
I tried adding another rangeVal with Integer type and the min,max values, and put them both in the same ValidationGroup, but that didnt work.
How do I allow the user to use both (either one of them) formats in the date input field.
Thank you in advance!
When you use multiple validation controls to validate a single control all of the validation controls must pass.
You could use a regular expression (as Kevin points out) but doing the validation you require (checking that the value is a valid DateTime object and within the specified range) will be difficult to do cleanly.
I'd suggest writing your own CustomValidator control and then use that to validate your values however you want to.
You can use a regular expression validator in place of the range validator. I'm a little rusty with Regex, but I am sure you can find something here.
http://www.regular-expressions.info/
Here is a link to the dates page:
http://www.regular-expressions.info/dates.html
try this, I think it will work. If not, let me know and I will work on correcting it:
((19|20)\d\d[- /.](0[1-9]|1[012])[-/.](0[1-9]|[12][0-9]|3[01])|((19|20)\d\d(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])))
Another post brought up a point this regex won't validate some invalid dates like feb 31. In this case, I would just create a validation class which inherits from the regex validator and override the EvaluateIsValid method and check to see if it is an actual date. This allows most of the validation done on the client end, with the backup being at the server level which should be doing a secondary validation anyway.

PHPs htmlspecialcharacters equivalent in .NET?

PHP has a great function called htmlspecialcharacters() where you pass it a string and it replaces all of HTML's special characters with their safe equivalents, it's almost a one stop shop for sanitizing input. Very nice right?
Well is there an equivalent in any of the .NET libraries?
If not, can anyone link to any code samples or libraries that do this well?
Try this.
var encodedHtml = HttpContext.Current.Server.HtmlEncode(...);
System.Web.HttpUtility.HtmlEncode(string)
Don't know if there's an exact replacement, but there is a method HtmlUtility.HtmlEncode that replaces special characters with their HTML equivalents. A close cousin is HtmlUtility.UrlEncode for rendering URL's. You could also use validator controls like RegularExpressionValidator, RangeValidator, and System.Text.RegularExpression.Regex to make sure you're getting what you want.
Actually, you might want to try this method:
HttpUtility.HtmlAttributeEncode()
Why? Citing the HtmlAttributeEncode page at MSDN docs:
The HtmlAttributeEncode method converts only quotation marks ("), ampersands (&), and left angle brackets (<) to equivalent character entities. It is considerably faster than the HtmlEncode method.
In an addition to the given answers:
When using Razor view engine (which is the default view engine in ASP.NET), using the '#' character to display values will automatically encode the displayed value. This means that you don't have to use encoding.
On the other hand, when you don't want the text being encoded, you have to specify that explicitly (by using #Html.Raw). Which is, in my opinion, a good thing from a security point of view.

Categories