ASP.NET: how to validate - asp.net

I have a simple ASP.NET (VB) page with a CompareValidator. I can check to ensure the value is numeric, but I have no idea how to check for the length (business rules require a 7 digit number). Existing code is below:
<asp:TextBox ID="txtPolicyNo" runat="server"
BorderStyle="Ridge"></asp:TextBox>
<asp:CompareValidator ID="cvCheckPolicy" runat="server"
ErrorMessage="Must be a valid policy number" ControlToValidate="txtPolicyNo"
Type="Integer" Operator="DataTypeCheck">
</asp:CompareValidator>
How can I accomplish this?
Thanks,
Jason

Use a RegularExpressionValidator with a regex string like "^\d{7}$". That will ensure you get a 7 digit number. You might have to combine that with a RequiredFieldValidator to make sure they enter something.

To Check business rules, the CustomValidator is normally used.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="invalid text"></asp:CustomValidator>
But if you only want to validate 7 digits, you can use RegularExpressionValidator with the validation expression: ValidationExpression=^\d{7}$

Use a RangeValidator or RegularExpressionValidator
<asp:RangeValidator id="rvCheckPolicy"
ControlToValidate="txtPolicyNo"
MinimumValue="1000000"
MaximumValue="9999999"
Type="Integer"
EnableClientScript="false"
ErrorMessage="Must be a valid policy number"
runat="server"/>
<asp:RegularExpressionValidator id="revCheckPolicy"
ControlToValidate="txtPolicyNo"
ValidationExpression="\d{7}"
ErrorMessage="Must be a valid policy number"
runat="server"/>

Related

ASP.NET "stacked" regular expression field validators

I have 2 ASP.NET regular expression validators:
^\s*[-+.'\w]+#\w+(?:[-.]\w+)*\.(?!co\s*$)\w{2,}\s*$ check whether the email address is valid
#(adres.pl|vp.pl) check if value contains any of these strings
The problem now is:
The strings in bullet 2 above should NOT be allowed, so o email address "john#adres.pl" should not be allowed.
However, the validators are only positive, meaning that they check if they DO contain the structure.
So when someone currently enters "test#test.com", I get "invalid value"
My code below:
<asp:TextBox ID="tbEmail" runat="server" />
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="emailinvalid" ValidationExpression="^\s*[-+.'\w]+#\w+(?:[-.]\w+)*\.(?!co\s*$)\w{2,}\s*$" ID="rev1" runat="server"/>
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="not allowed" ValidationExpression="#(adres.pl|vp.pl)" ID="rev2" runat="server"/>
I was initially thinking of combining expressions 1 and 2, but then I wouldn't know which one fails, and don't know which error to display.
What I would expect is:
"35435gd" -> emailinvalid
"john#adres.pl" -> not allowed
"john#gmail.com" -> all validators are ok
Or perhaps validator rev2 should only execute if rev1 does not throw an error, so "stacking" for a lack of a better term, which a: seems cumbersome and b: I wouldn't know how to do it.
How can I solve for this?
UPDATE 1
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="invalid" ValidationExpression="^\s*[-+.'\w]+#(?!(?:adres|vp)\.pl\b)\w+(?:[-.]\w+)*\.(?!co\s*$)\w{2,}\s*$" ID="RegularExpressionValidator5" runat="server"/>
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="not allowed" ValidationExpression="#(?!(?:adres|vp)\.pl\b)" ID="RegularExpressionValidator4" runat="server"/>
"gddg" results in "not allowed", whereas I'd expect "invalid".
When I switch the order of these validators, both errors "invalid" and "not allowed" show.
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="invalid" ValidationExpression="^\s*[-+.'\w]+#(?!(?:adres|vp)\.pl\b)\w+(?:[-.]\w+)*\.(?!co\s*$)\w{2,}\s*$" ID="RegularExpressionValidator5" runat="server"/>
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="not allowed" ValidationExpression="#(?!(?:adres|vp)\.pl\b)" ID="RegularExpressionValidator4" runat="server"/>
You can use a single pattern and you might write your existing pattern as:
^\s*[-+.'\w]+#(?!(?:adres|vp)\.pl\b)\w+(?:[-.]\w+)*\.(?!co\s*$)\w{2,}\s*$
The part excluding either adres.pl or vp.pl can be written as #(?!(?:adres|vp)\.pl\b) excluding those matches directly after the #.
You could also use #(?!(?:adres|vp)\.pl\s*$) if that is the last part of the email address just like you currently do for this part \.(?!co\s*$)
See a regex demo.
Note that your pattern would allow leading and trailing whitespace chars for the e-mail address.

RegularExpressionValidator asp.net

I am trying to make sure that user only can input a-z and 0-9 characters.
To do this I have used the RegularExpressionValidator class:
<asp:TextBox ID="input" Text="search" runat="server" OnTextChanged="searchFunc"></asp:TextBox>
<asp:RegularExpressionValidator ID="regExp" runat="server"
ErrorMessage="only a-z or 0-9 allowed"
ControlToValidate="input"
ValidationExpression="^[a-z0-9]+$" />
Though in the code behind I am trying to check if the user entered valid input by using
regExp.IsValid
But this method returns True even if user inputs !&%()
I can't understand what I've done wrong. Is it my regular expression that is wrong?
Call regExp.IsValid only after the validation has been performed otherwise the default value is set to true.
Try calling regExp.Validate() before checking the IsValid property.

mm/dd/yyyy regex for Regular Expression Validator in ASP.Net failed to validate

I know such questions are in ton and it feels like a dupe question. As I haven't found the solution closed to me, thats why i am posting this. I have a regex in my regular exp validator
<asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" ErrorMessage="Invalid date format. Valid dates are 12/31/2009 (mm/dd/yyyy). " ControlToValidate="txtDOB" Display="None" EnableTheming="False" EnableViewState="False" SetFocusOnError="True" ValidationGroup="grpUser"
ValidationExpression="^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-./])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$"></asp:RegularExpressionValidator>
Its failing to validate the date in mm/dd/yyyy or m/d/yyyy format. I have taken this from RegexLib where the author said its valid for both formats. Are the ^ and $ creating issues. Please help.
Unless you have a good reason to do otherwise, you should use a CompareValidator
<asp:CompareValidator Operator="DataTypeCheck" Type="Date" ...
This is working
^(0?[1-9]|[12][0-9]|3[01])[\/](0?[1-9]|1[012])[\/]\d{4}$
<asp:RegularExpressionValidator
ValidationExpression="^([0-9]|0[1-9]|1[012])\/([0-9]|0[1-9]|[12][0-9]|3[01])\/(19|20)\d\d$"
ControlToValidate="txtDOB" ErrorMessage="Invalid Format. Use MM/DD/YYYY" runat="server"
ValidationGroup="Password" CssClass="colorred">
</asp:RegularExpressionValidator>
this works for both m/d/yyyy and mm/dd/yyyy with valid dates

how to validate MaskedEditExtender control for MM/dd/yyyy format?

I am using maskedEditExtender control for getting date..
Code inside MaskedEditExtender is
cc1:MaskedEditExtender ID="MaskedEditExtender1" runat="server" TargetControlID="ui_txtRequestDateTime" ClearMaskOnLostFocus="false" Mask="99/99/9999 99:99" UserTimeFormat ="TwentyFourHour">
I need DateTime in MM/dd/yyyy hh:mm formate ,If i use calenderExtender control i can use Format="MM/dd/yyyy" ,but here i couldt specify the format MM/dd/yyyy, its generally "99/99/9999 99:99" format, the 1st two 9's for month, how to tell to user that they have to give month only, if i give value above 12, like 23,24 its showing exception..
Please give some idea..
Use RegularExpression validator with your textbox as follows:
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="valRegDate" ValidationGroup="OrderAdd"
ControlToValidate="txtDate" runat="server" ErrorMessage="Please provide a valid date."
ForeColor="Red" ValidationExpression="^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$"></asp:RegularExpressionValidator>

In asp.net, I need to add validator to textbox that forces the input to be numbers

In asp.net, I need to add a validator to a textbox that forces the input to be numbers.
Is this built in?
I have already added a required field validator to the textbox.
You could use a Regex Validator to ensure the text is numeric
I think the regex would be
[0-9]*
e.g.
<asp:TextBox ID="tbxNumbers" runat="server" />
<asp:RegularExpressionValidator ID="revNumericValidator" runat="server"
ValidationExpression="^[0-9]*$" ControlToValidate="tbxNumbers" ErrorMessage="Must be Numeric" />
EDIT:
As the other two posters also pointed out you can also use \d to represent a Numeric Character
<asp:RegularExpressionValidator runat="server"
ControlToValidate="numbersOnlyTextBox"
ErrorMessage="Enter only numeric characters."
ValidationExpression="^\\d+$" />
Use a range validator.
<asp:TextBox ID="MyTextBox" MaxLength="4" Width="75"
Text="0" runat="server"></asp:TextBox>
<asp:RangeValidator ID="MyRangeValidator" Display="Static" Type="Integer"
MaximumValue="9999" MinimumValue="0" EnableClientScript="true"
ControlToValidate="MyTextBox" runat="server" SetFocusOnError="true"
ErrorMessage="Ooops"></asp:RangeValidator>
This permits you to use numbers with decimal places (by using Type="Double" or "Currency"), or other kinds of numbers that Windows recognizes.
Check MSDN for more info on the Range Validator Control.
I think there needs to be more clarification of the requirements here. What kind of numbers are we talking about? Positive integers? Any integer? A number with a decimal place? What about commas in the number (1,000)?
I recommend a RegularExpressionValidator to do your work, but these questions make a difference when it comes to which RegEx you use.
In order to provide a better user experience, another thing to add is an AjaxToolkit FilteredTextBox extender, with a FilterType of either "Custom, Numbers" or just "Numbers". The first choice is for when you want to be able to specify decimal points and negative numbers. In that case you must also specify the ValidChars attribute with something like "-.". This will stop a user from entering characters that are not going to make up a valid number such as -123.45 . Note that it does not stop the user from entering the '-' & '.' in incorrect places e.g. "2-..-3" can still be entered. You will need the validators mentioned in other answers to catch these cases.
<ajaxToolkit:FilteredTextBoxExtender ID="ftbe" runat="server"
TargetControlID="numbersOnlyTextBox"
FilterType="Custom, Numbers"
ValidChars="-." />
Or
<ajaxToolkit:FilteredTextBoxExtender ID="ftbe" runat="server"
TargetControlID="numbersOnlyTextBox"
FilterType="Numbers" />

Resources