FormView not saving due to RegularExpressionValidator grouping issue in expression - asp.net

I have the following regular expressions, used to pick up a specific domain name and email address type:
(?i:^domain\\[a-z0-9]+$)
(?i:([;]|^)([a-z0-9.]+#(dom\.net|part1\.part2\.uk))(?=[;]|$))
I'm using them in a pair of RegularExpressionValidator controls on an ASP.NET page to do the obvious.
The two expressions have been tested (first, second), and work fine. I've even tested them on regexstorm.net/tester, and they work fine there, too, or rather, it didn't complain at all.
I've tried entering data correctly and incorrectly into the text boxes, which does produce the desired result (i.e. showing and hiding the validator messages).
When I come to submit the changes for the data to be saved away, though, nothing happens.
This thread in the ASP.NET forums showed me that the issue could be related to an incorrectly defined expression. After testing and pulling the results from the developer tools with Chrome, sure enough I did find an exception listed, quoting an incorrect group expression (e.g:):
Uncaught SyntaxError: Invalid regular expression:
/(?i:([;]|^)([a-z0-9.]+#(dom\.net|part1\.part2\.uk))(?=[;]|$))/:
Invalid group
at new RegExp (<anonymous>)
at HTMLSpanElement.RegularExpressionValidatorEvaluateIsValid [as evaluationfunction] (ScriptResource.axd?d=nv7asgRUU0tRmHNR2D6t1I81CZYvhDRBNs2fZ336VJmjaWUtfpNHyosZQUxZ0B5WPXmV97rd4uGrASTweyiB-WOW1uyNsuPtZ3w36cKlE-LnO2_rZ0xo0PpdoCQY_z4Id3GA-_iewMRfjN0CNhHZOQ2&t=26028d1e:458)
at ValidatorValidate (ScriptResource.axd?d=nv7asgRUU0tRmHNR2D6t1I81CZYvhDRBNs2fZ336VJmjaWUtfpNHyosZQUxZ0B5WPXmV97rd4uGrASTweyiB-WOW1uyNsuPtZ3w36cKlE-LnO2_rZ0xo0PpdoCQY_z4Id3GA-_iewMRfjN0CNhHZOQ2&t=26028d1e:200)
at ValidatorOnChange (ScriptResource.axd?d=nv7asgRUU0tRmHNR2D6t1I81CZYvhDRBNs2fZ336VJmjaWUtfpNHyosZQUxZ0B5WPXmV97rd4uGrASTweyiB-WOW1uyNsuPtZ3w36cKlE-LnO2_rZ0xo0PpdoCQY_z4Id3GA-_iewMRfjN0CNhHZOQ2&t=26028d1e:162)
at HTMLInputElement.eval (eval at ValidatorHookupEvent (ScriptResource.axd?d=nv7asgRUU0tRmHNR2D6t1I81CZYvhDRBNs2fZ336VJmjaWUtfpNHyosZQUxZ0B5WPXmV97rd4uGrASTweyiB-WOW1uyNsuPtZ3w36cKlE-LnO2_rZ0xo0PpdoCQY_z4Id3GA-_iewMRfjN0CNhHZOQ2&t=26028d1e:90), <anonymous>:3:1)
Unfortunately, I simply don't know enough about regex to be able to figure out just where the expression is breaking down - I would really appreciate some pointers.
The ASP.NET page code for the related text boxes and validators...
<asp:Label runat="server" ID="labelDomainUsername"
Text="Your domain username..." AssociatedControlID="textDomainUsername"
ClientIDMode="Predictable" />
<span class="help">
This is your Windows login, and usually appears as <strong>DOMAIN\asurname</strong>.
</span>
<asp:TextBox runat="server" ID="textDomainUsername"
Text='<%# Bind("domain_username")%>'
CssClass="mandatory w2Eighths noBlock"
PlaceHolder="DOMAIN\AUsername" TabIndex="0" />
<asp:RegularExpressionValidator runat="server" ID="rexDomainUser"
ControlToValidate="textDomainUsername"
ValidationExpression='<%$ appSettings:rexDomainAccount %>'
Text="Please supply a valid domain username."
CssClass="validBalloon" Display="Dynamic" />
<asp:Label runat="server" ID="labelEmail"
Text="Your email address..." AssociatedControlID="textEmail" />
<span class="help">
Your email address can be an <strong>dom.net</strong> or <strong>part1.part2.uk</strong>
account. If you have a secretary, or wish to include another email address separate them with a
semi-colon.
</span>
<asp:TextBox runat="server" ID="textEmail" Text='<%# Bind("email")%>'
CssClass="mandatory w3Eighths noBlock" AutoCompleteType="Email"
PlaceHolder="any.username#dom.net" TabIndex="1" />
<asp:RegularExpressionValidator runat="server" ID="rexEmail"
ControlToValidate="textEmail"
ValidationExpression='<%$ appSettings:rexEmailAddress %>'
Text="Please supply a valid email address."
CssClass="validBalloon" Display="Dynamic" />

As pointed out, there are certain issues with utilising the RegularExpressionValidator. There are multiple ways around the issue, but all I've done is replace it with a CustomValidator and validate the parts of the string that I needed too.

Related

validating input to the asp:CreateUserWizard control

I'm using the asp:CreateUserWizard control and have read on MSDN:
User input in a Web page can potentially contain malicious client
script. By default, ASP.NET Web pages validate user input to ensure
that the input does not contain HTML elements or script. As long as
this validation is enabled
This is the code I'm using:
<asp:Label runat="server" AssociatedControlID="UserName">User name</asp:Label>
<asp:TextBox runat="server" ID="UserName" CausesValidation="true"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="UserName"
CssClass="field-validation-error" ErrorMessage="User name is required." />
<asp:RegularExpressionValidator runat="server" ControlToValidate="UserName"
CssClass="field-validation-error" ErrorMessage="User name must not contain \ (backslashes)."
ValidationExpression="[^\\]*" />
Now if I try and create a user with a name like <script>alert('hello')</script> my app then crashes with a 500 internal error.
I've tried code in all these events to see if I can trap the error but the code never gets hit:
RegisterUser_CreateUserError()
RegisterUser_CreatingUser()
So my 2 questions are, why is the input not being validated and where could I trap this error when it is thrown (the 2nd question maybe less important once I know how to do the first part)?
I must be missing something really simple here.

.net ascx control not retaining value on postback (mojoPortal)

I'm making a custom module for mojoPortal CMS which needs to allow the client to add an affiliate into the database. As far as I can tell, this requires creating a .ascx file and then installing that using the administration toolbar in the Web interface to get it to a point where I can put it into a page, as http://www.mojoportal.com/hello-world-developer-quick-start.aspx.
The form is simple enough, but the values in the text boxes just stay empty when I submit, though the file upload works fine. The code:
<asp:Label ID="Label1" runat="server" Text="Company Name" AssociatedControlID="CompanyName">
</asp:Label>
<asp:TextBox ID="CompanyName" runat="server"></asp:TextBox>
<asp:Label ID="Label2" runat="server" Text="Company Description" AssociatedControlID="CompanyDescription"></asp:Label>
<asp:TextBox ID="CompanyDescription" TextMode="MultiLine" runat="server"></asp:TextBox>
<asp:Label ID="Label3" runat="server" Text="Company Logo" AssociatedControlID="CompanyLogo"></asp:Label>
<asp:FileUpload ID="CompanyLogo" runat="server" />
<asp:Button ID="SubmitButton" runat="server" Text="Add Affiliate" />
EnableViewState for the page and the controls is enabled
The text box is not set to ReadOnly, and there is no funky JavaScript dynamically modifying elements (at least, I didn't set any).
I can work around this by using HTML elements, and get the values using Request.Form. The information is actually there, I can see it in the Request.Form, but I would have to get that by something like Request.Form[CompanyName.ClientId.Replace("_","$")] or Request.Form[6] which both seem very messy and IIRC aren't really the way things are supposed to roll in .NET. Besides, having worked until 3 last night, I really want to know what the answer is now!
Any thoughts anyone?
What I had done was not created a click event for the button, relying on the fact that it was posting to the server (like I would in PHP). Oops! When I added a click event, then the text boxes retained their value when I was within that method.

is it possible to validate a control in asp.net but not require it?

Is it possible to validate that it's a phone number but not require it? The way it is right now if I don't enter a number it will throw the error. I read somewhere that you can change the RegEx to do this and I tried by enclosing the RegEx in (?:...?)
<asp:TextBox runat="server" ID="tbCompanyFax" Width="99%" Text='<%# Eval("CompanyFax")%>'></asp:TextBox>
<ajaxTK:MaskedEditExtender runat="server" ID="maskCompanyFax" AutoComplete="false" TargetControlID="tbCompanyFax" Mask="(999)999-9999" ClearMaskOnLostFocus="false" />
<asp:RegularExpressionValidator ID="regCompanyFax" runat="server" ControlToValidate="tbCompanyFax" ErrorMessage="Invalid Fax number" ValidationExpression="(?:((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4})?" Display="None"></asp:RegularExpressionValidator>
Your problem arises from the mask being submitted.
You could allow the mask in your RegEx. That would save the trouble of having to write a custom validator.
Try this RegEx
(?:((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4})|(((\(\s{3}\) ?)|(\s{3}-))?\s{3}-\s{4})
Should make an empty mask valid
I tweaked #nunepascal's RegEx and it works exactly as I wanted.
Thanks again!
ValidationExpression="(?:(((\d{3}))|(\d{3}-))?\d{3}-\d{4})|((((_{3}))|(_{3}-‌​))?_{3}-_{4})"

Updating Database with value from datepicker control ASP.NET VB

Apologies in advance, for what may be a newbie question. (new to asp.net, coding in VB, zero knowledge of best controls). Please respect that I am not interested in AJAX controls, or using MVC and trying to minimise javascript. What I need to do is very simple in terms of technology.
I am developing a form that allows users to Edit database data. I have chosen to use FormView so that I can format it like a legacy vba app. I am able to set the data source to my database table and the values from the database successfully show up if I allow VWD to automatically format the control. I can edit everything in the database using this form as well.
However, the boss hates having to type dates.
I haven't been able to find a datepicker control with a datasource feature that works like the text boxes that are automatically built in formview (with a bind to a datasource feature). So, I am assuming none exist. I need some assurances that what I think I need to do is the right way.
Instead of using the FormView control's datasource via the front-end automagical stuff, I should instead
place one of these datapicker controls that simply combine calendar with a text box for all date fields in the formview (no disrespect to those who built them, just can't believe they are not more feature-rich, this seems so needed giving the number of datepickers available)
declare my data source in Page_Load and load all the controls if they have existing data utilising FindControl
use Data_Bound block to retrieve the selected values from each control utilising FindControl and build a dynamic SQL string for Update
declare and update my database using one of the code behind blocks, perhaps in the DataBound
Am I on the right track? I have no experience to be confident in my assumption.
and please, if there is an easier way, I'll take it, but I have to make it "pretty".
And suggestions for controls of any sort are welcomed.
---Further into my issue
Here is some code to prove I've actually tried to resolve this...
In my FormView code block I have:
<asp:FormView ID="FormView1" runat="server" DataKeyNames="MASTERID_Action"
DataSourceID="srcAction">
<EditItemTemplate>
MASTERID_Action:
<asp:Label ID="MASTERID_ActionLabel1" runat="server"
Text='<%# Eval("MASTERID_Action") %>' />
<br />
Action_Description:
<asp:TextBox ID="Action_DescriptionTextBox" runat="server"
Text='<%# Bind("Action_Description") %>' />
<br />
Action_Target:
<asp:TextBox ID="Action_TargetTextBox" runat="server"
Text='<%# Bind("Action_Target") %>' />
<br />
Action_Captured:
<asp:TextBox ID="Action_CapturedTextBox" runat="server"
Text='<%# Bind("Action_Captured") %>' />
<br />
Action_Declined:
<asp:TextBox ID="Action_DeclinedTextBox" runat="server"
Text='<%# Bind("Action_Declined") %>' />
<br />
Action_AgreedDate:
<ewc:CalendarPopup ID="CalendarPopup1" runat="server" Culture="en-AU"
PostedDate="" SelectedDate='<%# Bind("Action_AgreedDate") %>'
SelectedValue="01/14/2013 08:47:54" UpperBoundDate="12/31/9999 23:59:59"
VisibleDate="01/14/2013 08:47:54" />
<br />
...
</EditItemTemplate>
My database holds this Action_AgreedDate as nullable.
When I view the ItemTemplate (in the browser) the date shows up as 0.000 (because its a text field and bound to Action_AgreedDate, no error occurs) and when I click Edit to go to the EditItemTemplate I get this error:
Conversion from type 'DBNull' to type 'Date' is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Conversion from type 'DBNull' to type 'Date' is not valid.
Source Error:
Line 95:
Line 96: Action_AgreedDate:
Line 97: '
Line 99: SelectedValue="01/14/2013 08:47:54" UpperBoundDate="12/31/9999 23:59:59"
I can easily translate this into "the control found a null field and doesn't know what to do with it"; problem is, I don't know what to do. I have checked the properties of the field (the CalendarPOP field to see if there is a setting for handling nulls and nothing is obvious to me. I'm currently trying to find further documentation on the control online. (I've contacted eWorld and hope they will be able to respond.)
I should also add that if I request a record that already has an Action_AgreedDate I get no errors because there is a value present in the database for the control to display.
I think the best way for you to do this would be to use jQuery and jQuery UI, which has a date picker, which can be attached to a regular ASP.NET TextBox in your FormView. So if you had FormView code that looks something like this for example:
<asp:FormView ID="FormView1" runat="server" DataKeyNames="id" DataSourceID="SqlDataSource1">
<EditItemTemplate>
id:
<asp:Label ID="idLabel1" runat="server" Text='<%# Eval("solution_id") %>' />
<br />
date_modified:
<asp:TextBox ID="date_modifiedTextBox" runat="server" Text='<%# Bind("date_modified") %>' />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<ItemTemplate>
id:
<asp:Label ID="idLabel" runat="server" Text='<%# Eval("solution_id") %>' />
<br />
date_modified:
<asp:Label ID="date_modifiedLabel" runat="server" Text='<%# Bind("date_modified") %>' />
</ItemTemplate>
</asp:FormView>
You could run something like this using jQuery UI to get a datepicker on the date_modified text box:
$('[id$=date_modifiedTextBox]').datepicker()
The $('[id$=date_modifiedTextBox]') part is necessary to select the ASP.NET control using jQuery, if it were just a normal element you could just use $('.className') or $('#id') or something like that. Hope this helps.
Problem solved.
I ran across an article on 4GuysFromRolla.com about the RJS POP Calendar (http://preview.tinyurl.com/cerm9xv) and it ticked all the boxes. Successfully implemented it and, because the calendar is separate from the specified text box, it doesn't have to be bound ! It works very nicely. The 4GuysFromRolla save my bacon yet again...

Regular expression multiline validator

In my ASP.NET Web Form I have a multiline TextBox which should be validated with RegularExpression Validator. Text box should contain one or more strings "a" (just 'a' char, nothing else).
So far I got these regular expressions for my RegularExpressionValidator object:
(?m:(^a$)+)
(?m:\A(^a$)+\Z)
(?m:^a$)
and some others. Neither works. Guess there is something fundamental I'm not getting yet.
Could you please tell me where I'm wrong?
Here's the code involved.
A Button (just for postbacks):
<asp:Button ID="Button1" runat="server" Text="Button" />
The TextBox:
<asp:TextBox ID="TextBox1" runat="server" Rows="10" TextMode="MultiLine"></asp:TextBox>
And the regex validator:
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="RegularExpressionValidator"
ValidationExpression="(?m:(^a$)+)"></asp:RegularExpressionValidator>
There is nothing else on that Web Form. I've only added those controls and modified properties. I've even did all this using VS GUI.
Using CustomValidator and doing Regex.Match(TextBox1, #"(?m:(^a$)+)") in it works just fine. Something is wrong with RegularExpressionValidator I guess.
If you want to match multiple lines, don't forget to also match the line terminators; they are not implied in $.
(?m:(^a$\r?\n?)+)
might work better.
This matches
a
or
a
a
a
etc.
And, since you're asking for a tutorial, how about regular-expressions.info?

Resources