Efficient/Easy method to validate for empty text boxes? - c#

I have a about 6 or 7 text boxes which needs to be validated to make sure they are not empty from server side code. So how I usually do this is, check each textbox 1 by 1 to ensure that they are not empty. Are there any other efficient methods to do this? I have searched on SO and have found out that adding all the textboxes to a list and using a for each is a much better method. Are there any other ways that this can be achieved? Thanx a lot in advance :)

Just check them each individually:
if (string.IsNullOrEmpty(this.NameTextBox.Text) ||
string.IsNullOrEmpty(this.AddressLine1TextBox.Text) ||
// etc...
)
{
// Handle me
}
Or possibly:
void CheckTextBox(TextBox textBox)
{
if (textBox == null)
{
throw new ArgumentNullException("textBox");
}
if (string.IsNullOrEmpty(textBox.Text))
{
// Handle me
}
}
void Validate()
{
CheckTextBox(this.FirstNameTextBox);
CheckTextBox(this.AddressLine1TextBox);
CheckTextBox(this.AddressLine2TextBox);
}
7 text boxes really isn't that many - explicitly checking each one keeps it simple and makes sure that others reading your code know what's going on, whereas messing around with collections is adding another layer of indirection, and makes it just slightly less straightforward to debug.
Keep it simple!

I agree with Kragen - your code may look "big" because of all the checks, but you are really writing exactly what the program needs to do in order to validate these things, so any sort of clever approach that reduces the number of lines of code you write isn't actually going to speed things up that much.
Question though: do you have to validate the textbox on the server? If you are only validating that the textbox isn't empty, I'd suggest using client side validation. That will save you server time and bandwidth, since your user won't be allowed to submit the form to your server until their browser has validated that they aren't empty.
You'd still want to validate on the server side (in case they don't have JavaScript enabled on their browser or they are attempting some kind of malicious behaviour).
The native ASP.NET way of client side validation involves adding an ASP.NET validation tag to your ASPX. It's actually quite easy. Here's an example on MSDN:
http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic3
I've simplified their code a bit to match your requirements:
<form runat="server">
<asp:TextBox id="TextBox1" runat="server" />
<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Name is required!" ControlToValidate="TextBox1" />
<asp:TextBox id="TextBox2" runat="server" />
<asp:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ErrorMessage="Address is required!" ControlToValidate="TextBox2" />
<asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Button"></asp:Button>
</form>

Related

ASP.NET Javascript runtime error

I have just started a new ASP.NET web application and I am totally new to everything and after moving a few things round I have been getting this error and I don't understand what it means.
It happens when I go to enter anything in the Password box.
Could someone please help me out on this issue.
EDIT:
<li>
<asp:Label runat="server" AssociatedControlID="Password">Password</asp:Label>
<asp:TextBox runat="server" ID="Password" TextMode="Password" onkeypress="capLock(event)" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="Password" CssClass="field-validation-error" ErrorMessage="The password field is required." />
</li>
Try to do that inside
window.onload = function(){
// code goes here
}
I think you are trying to access DOM even before it is being created.
the document.getElementById('divMayus') is undefined
document.getElementById("divMayus") is returning null or undefined.
You should look at the rendered html and find the div that you are trying to reference to make sure the id is the same as you are trying to reach. Asp.net alters the ids of server controls depending on their containers. So if you moved stuff around, the id may have also been changed.

doPostBack not working properly

I am trying to post back on a button click.But unable to get __EVENTTARGET and __EVENTARGUMENT. It is currently always null. Is there any other entries I have to do?
aspx
<asp:Button ID="btn" runat="server" OnClientClick="GetDet();" Text="Click"/>
<script type="text/jscript">
function GetDet() {
var obj = $('.output');
var sign = $('.name'); //hidden field
__doPostBack('btn', sign.val());
}
</script>
.cs
string tar = Convert.ToString(Request.Params.Get("__EVENTTARGET"));
string val = Convert.ToString(Request.Params.Get("__EVENTARGUMENT"));
Instead of doing such a hack. I'd actually recommend you to do things the proper way so you can guarantee scalability because you never know what's gonna happen on the next release of ASP.NET and the ASP.NET Team certainly does not endorse these types of hacks, in other words, your hacks might break with a future releases of ASP.NET...always strive to avoid them. So, if you want to do a full postback you definitely don't need javascript for this....
<asp:Button ID="btn" runat="server" Text="Click"/>
Then, if you want to post the value of the hidden field simply add the hidden field to the form...
<asp:HiddenField ID="hdfName" runat="server" Value="whatever" />
if you want to read the value of the hidden field during the postback...
public override void OnLoad(EventArgs args)
{
var name = hdfName.Value;
}
That's how you are supposed to work with ASP.NET the proper way rather than trying to hack its intrinsics

use Javascript or C# to validate a webform

Would like to validate more than one control on one button click. I would like something to validate whether a textbox has contents if a checkbox is checked or not but the checkbox doesn't necessarily have to be checked and in that case I don't want to check the textbox. I tried validation group but each button needs to control the different groups and i need this all to be under one button.
I'm open to ideas of how to do this c#,javascript...etc. Heres some code: Button3 is the save which validates whether checkbox 1 is checked and if so textbox10 cant be empty. I have about four other instances of this but are independent of each other.
<asp:Button ID="Button3" runat="server" Height="24px"
Text="Save" Visible="False" Width="67px" Font-Bold="True"
causesvalidation="true"
validationgroup="required"
runat="Server" />
<asp:CheckBox ID="CheckBox1" runat="server"
oncheckedchanged="CheckBox1_CheckedChanged" Text=" Breach Letter Sent"
ValidationGroup="required" AutoPostBack="True" Enabled="False" />
You want to use the CustomValidator control which can validate both on the server and the client. There is an example in the docs here - http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.aspx
I would never do form validation in JavaScript. Believe it or not, but some people actually turn off JavaScript! Use validators to validate the field content. Of course this means a round trip to the server in most cases, but you get reliable and well integrated validation.
you can use validation with Ajax (in Ajax postback occures but you will not sense)

TextChanged event not firing

I have a GridView and a TextBox in one of its fields:
<asp:GridView ID="NTSBulkEditGridView" runat="server" AutoGenerateColumns="false" AllowSorting="true" Height="500px"
DataKeyNames="BookStem" OnRowDataBound="NTSBulkEditGridView_RowDataBound" DataSourceID="NTSSqlDataSource">
<Columns>
<asp:TemplateField HeaderText="Priority" SortExpression="Priority">
<ItemTemplate>
<asp:TextBox ID="txtPriority" runat="server" Text='<%# Eval("Priority") %>' BorderStyle="None" Width="80%" OnTextChanged="TextBox_Changed" AutoPostBack="true"></asp:TextBox>
<asp:CompareValidator ID="PriorityCompareValidator" runat="server" ControlToValidate="txtPriority" Display="Dynamic" ErrorMessage="Priority must be an integer!" Text="*" Operator="DataTypeCheck" Type="Integer" ValidationGroup="InsertUpdateNewTitlesStatusValidation" ></asp:CompareValidator>
</ItemTemplate>
</asp:TemplateField>
...
Could you please tell me why TextBox_Changed() is never called when I change text and press Enter? I tried to put same kind of a TextBox outside of the GridView, and there it works.
Thanks.
TextChanged of an ASP.NET TextBox translates into blur JavaScript event. And blur occurs when the text of the input element is changed and the input element loses focus. Try to change the text, but don't hit Enter. Simply hit TAB key to go to next field. Does it fire post back?
Update:
Well, I saw that link. Two things. First, if you notice, it goes back to 2005 and ASP.NET 2.0 and we all know that 6 years in the world of computer means 60 years. So that article is obsolete by now. Second, sometimes a pattern only exists in articles, and you rarely see it in real productive systems. How many bulk actions have you seen on the web? And what type do they have? Consider Gmail, or Yahoo mail for example. You can mark 20 or 30 or X number of emails as read in one shot. But, can you respond to 20 mails in one step? Nope, just because it doesn't make sense. I've never seen a bulk action on a text box in web world. I think you'd better stick to use AJAX, with better performance, and more user acceptance. :)

Handling the submit action of two TextBoxes

I have an ASP.net page.
That has an Ajax Toolkit Tab Control.
That has tabs.
That have custom ascx controls I wrote.
I have a text box that perform a search action. It is declared like this:
<asp:TextBox ID="txtPrereqSearch" runat="server"
ontextchanged="txtPrereqSearch_TextChanged"></asp:TextBox>
Nothing fancy. This format has been working for months. There's no submit button. It just posts back when I hit enter. The problem appeared when I added a second custom control using the same type of feature. Now browsers don't postback when I type something in either of these textboxes and press enter.
It seems that browsers have a default way of handling one textbox in one form, but that behavior changes when the number reaches two.
Is there an easy way around this? I guess I can create a hidden submit button but it seems like there is probably a better way to deal with this when the functionality is in two separate custom controls.
Your feedback is appreciated!
Check this out: http://www.allasp.net/enterkey.aspx
The default behavior with no submit button seems to depend on the browser, and the behavior can indeed depend on the number of input controls.
I would add hidden "submit" button (e.g. style="display:none;") which should ensure that it always gets submitted.
The answer was a little different than I expected, but philosophically like my original idea that #jamietre reinforced.
I had to surround the controls with an <asp:Panel> tag with a DefaultButton attribute. A-like-a so:
<asp:Panel ID="ButtonPanel" runat="server" DefaultButton="btnSubmit">
<asp:Label ID="Label1" runat="server" Text="Course:"></asp:Label>
<asp:TextBox ID="txtPrereqSearch" runat="server"
ontextchanged="txtPrereqSearch_TextChanged"></asp:TextBox>
<asp:TextBoxWatermarkExtender ID="txtPrereq_TextBoxWatermarkExtender"
runat="server" Enabled="True" TargetControlID="txtPrereqSearch"
WatermarkCssClass="Watermark" WatermarkText="e.g., MATH201"></asp:TextBoxWatermarkExtender>
<asp:Button ID="btnSubmit" CssClass="InvisibleSubmit" runat="server" Text="Submit" OnClick="txtPrereqSearch_TextChanged"/>
</asp:Panel>

Categories