Hello guys,
since I have now effectively completed my first asp.net application (it's a very basic application where people...ahem, where I can record overtime) I was wondering what the best way is to add some validation. The page which allows you to upload the details needed (date, hours worked and comments) is very simple but two of the fields (date and hours worked)need to be validated. Being as I have many times repeated at the very beginning of my asp.net/visual studio/C#/SQL trip, I thought I'd take a look at some of the Visual Studio 3.5 inbuilt validations but I soon discovered that they are very limited (oh unless you can download more of course): I added. So, I was hoping to get some advice as to what to do.
Here is a screenshot of the input page, I thought it'd be nice to put things in context:

Basically I need the date and hours fields to be validated against no input and invalid input and I have no idea what to do and what to use. THe date fields should be input in any this format 30/12/2014 or 30/12/2014 or 30.12.2014 or 30/12/14 etc (obviously any advice is accepted) and the hours should be in the range 0-168 (which I could do easily in visual studio with the range validation but then I realized that somehow it had to include the possibility that the field was empty, so I discarded the inbuilt range validation).
Ah, the source code of that page is here, just in case, I don't know
http://pastebin.com/aAfDksUB (Default.aspx)
http://pastebin.com/D8thkAFG (Default.aspx.cs)

Recommended Answers

All 20 Replies

THe date fields should be input in any this format

Is there a specific reason you haven't used a DateTimePicker?

For an empty field you can use the RequiredFieldValidator. You can add as many validators to a field as you please. There's also the CustomFieldValidator if you want something specific.

Thanks.

Is there a specific reason you haven't used a DateTimePicker?

I suppose I had no idea there was one, sorry. Does it involve a lot of changes in code/C#/SQ? I just checked in the toolbox, but there is no DateTimePicker, where do I find it?

For an empty field you can use the RequiredFieldValidator. You can add as many validators to a field as you please.

Right, I had a look at all those inbuilt validation tools already, and I did actually add the range validator only, but since I then needed another one to make sure that the input was only a number, and the field not empty, I thought it was impossible to do with the inbuilt tools. SO just to summarize then: for the hours worked, I can add the range validation + the RequiredField and what about the fact that the input can only be a number (or is that included in the range validation)?
thanks

I can add the range validation + the RequiredField and what about the fact that the input can only be a number

You could choose to use a CustomValidator and do all those checks in code. Am not sure if the range validator does a numeric check, but I think it does.

To validate a data type use the CompareValidator.

I think my datepicker comes from:
https://ajaxcontroltoolkit.codeplex.com/documentation

Microsoft has this:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.calendar.aspx

OK thanks

You could choose to use a CustomValidator and do all those checks in code.

Now, say that for whatever reason I wouldn't want to use a customValidator, you said I could use as many validators as I want to, so theoretically, I could have both the range validator and the required field one with 2 separate error messages? I had a quick look at the custom validator, but it would appear that you have to write all the validation code yourself, which isn't necessarily a problem but I suppose I will have to find out how c# deals with strings, integers and empty fields.

I also had a look at the calendar: it's good but the one inbuilt in visual (the link to microsoft) is a calendar and not a date picker as such, so I would have to have a calendar displayed on the page all the time which might not be the best thing in my case. The other one seems more promising https://ajaxcontroltoolkit.codeplex.com/wikipage?title=Displaying%20a%20Simple%20Popup%20Calendar&referringTitle=Calendar%20Control and it displays a calendar when you click on the input field, so I may download and use that (I suppose it doesn't even require any database change because the date will be the value of the input field and the current code for populating the sql database should work)

so theoretically, I could have both the range validator and the required field one with 2 separate error messages?

Correct.

I also had a look at the calendar

Sorry about that, I have so many tools installed I often forget it's not native to .NET.

No problem, no need to be sorry :-). OK so I'll have a look at all that then and will post back if I get stuck. Thanks for your help

With the asp.net validators, you should have all of your bases covered. Overtime, you'll find the custom validator to be your friend once you learn a bit if regex.

Um...I am not that keen to learn regex...that's why I was asking about using more than one validator ont he same element...will see anyway, tackling the date picker now

@pritaeas, sorry just to pick up on something you've said earlier:
To validate a data type use the CompareValidator.
I had a look at the compareValidator but it looks like it allows you to compare 2 separate fields, not just one. What I mean is, say you have 2 input fields where you are asked to insert the password and to confirm it, then you can use that validator to compare the two fields. But can it alse be used to validate one field like in my case (I need to validate the date inserted using the date picker)
thanks

DateTime.Now.ToString("dd/MM/yyyy"); or use a DateTimePicker or Calendar Control. Tip: Make use of Control events to add more validation.

But can it alse be used to validate one field

No, for a single field it can only do a data type check (AFAIK).

Something that hasn't been mentioned but worth bringing up regarding asp.net validation controls...not only do they handle client side validation, but they also take care of server side validation in the event that javascript is disabled on the browser.

Validating server side is very important.

Thanks guys, so just to clear up this date picker thingy: I got it to work finally, and now I am looking at the validation. Since the field cannot be empty and I need the value to be in a certain format, I will use the custom validator. In terms of how to validate (I'm talking about the actual functions to use) I discovered this calendar has this handler "OnClientDateSelectionChanged" that I could use. Making sure the box isn't empty should be straightforward (I think it's a good time to say that I've never done validation before), as I could have a function that does that, like

private void checkField(object sender, EventArgs e){
    if(txtStartDate.Value==""){
    //how do I show an error message?
    }
}

but I'm not sure how to show an error message: I mean is it a message that sits in the page and gets shown/hidden as needed?
Then, to parse the string, do I need a regular expression (god help me!)?
cheers

Er, more importantly, I was thinking to how to trigger the validation. Let me explain. At the moment I have an html button that has an onserverclick="submitData" which calls the submitData function that has all the code for inserting stuff into the database: <input id="Submit1" type"submit" value="submit" runat="server" onserverclick="SubmitData">. In my aspx file I have inserted a customValidator controller, assigned an event handler to it like so <asp:CustomValidator ID="CustomValidator1" OnServerValidate="CheckString" runat="server" ErrorMessage="bla bla bla" ControlToValidate="txtStartDate"></asp:CustomValidator>, and in my code behind the CheckString function will contain the validation

protected void CheckString(object sender, ServerValidateEventArgs e){
MessageBox.Show("function called");
}

So I submitted the form but the CheckString function didn't get called, so my question is, how do I call that function? Do I call it also from the submit button adding it in the event handler like so
<input id="Submit1" type"submit" value="submit" runat="server" onserverclick="SubmitData, CheckString">?
thanks

Server-side you can call:

Page.Validate();
if (Page.IsValid)
{
   // All validators are valid
}

OK thanks, so that, I suppose, needs to be done after the validation has been done to check whether the validation has been passed, but how do I kick the validation off in the first place? As I said above the customValidator has this handler OnServerValidate="CheckString" and this is the method

protected void CheckString(object sender, ServerValidateEventArgs e){
MessageBox.Show("function called");
}

so I would have thought that was enough to get the function to run, but it doesn't. Does it mean that I need to kick things off from the submit button (it would seem more logical), but how since the submit button already has one event handler <input id="Submit1" type"submit" value="submit" runat="server" onserverclick="SubmitData">?
thanks

how do I kick the validation off in the first place?

Line 1 above triggers the validation. If you put that first in your SubmitData event handler, all validators should be triggered.

Thanks but I still have problems with the validation, this thing is really doing my head, lol. OK so here is the code, as it might be easier and clear any confusion:
Default.aspx:

<div class="control-group">        
<label class="control-label" for="week1">Week ending</label>
<div class="controls">
<!--<input type="text" id="week" runat="server">-->
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:TextBox ID="txtStartDate" runat="server"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtStartDate" Format="dd/MM/yyyy">
</asp:CalendarExtender>
<asp:CustomValidator ID="CustomValidator1" OnServerValidate="CheckString" runat="server" ErrorMessage="Needs to be a dd/mm/yyyy string" ControlToValidate="txtStartDate"></asp:CustomValidator>
</div>

</div>           
<div class="buttons">
<input id="Submit1" type="submit" value="Submit" runat="server"  onserverclick="submitData"/>
<input id="Submit2" type="submit" value="Reset" runat="server" onserverclick="clearData"/>
<input id="Submit3" type="submit" value="Empty database" runat="server" onserverclick="clearTable"/>
</div>

This is where I added the customValidator.
Now the Default.aspx.cs
As you said, I added the above code at the top of the submitData method although I am not sure what goes in it, but anyway then I attempted some validation inside the CheckString method at the bottom: I created a string variable and assigned to it the text of the field I want to validate: if it's empty then e.isValid is false, but I can't get it to work - I've probably done something stupid just for a change.

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Windows.Forms;//allegedly for messageBox

public partial class _Default : System.Web.UI.Page 
{
private SqlCommand sqlCmd;
private SqlConnection hookUp;
private string strInsert;
private const decimal WRKHRS = 37.5M;
private decimal HrsWorked;
private decimal Overtime;

protected void submitData(object sender, EventArgs e) {
Page.Validate();
if (Page.IsValid) { 

}


hookUp = new SqlConnection("Server=localhost\\SqlExpress;Database=test1;" + "Integrated Security=True");
strInsert = "INSERT INTO Overtime(Week,HrsWorked,Overtime,Comment) VALUES (@week,@hrsWrk,@ovt,@cmmt)";
HrsWorked = Convert.ToDecimal(hrs.Value);
Overtime = HrsWorked - WRKHRS;
sqlCmd = new SqlCommand(strInsert, hookUp);        
sqlCmd.Parameters.Add("@week", txtStartDate.Text);
sqlCmd.Parameters.Add("hrsWrk", HrsWorked);
sqlCmd.Parameters.Add("@ovt", Overtime);
sqlCmd.Parameters.Add("@cmmt", TextArea1.Value);        
hookUp.Open();
sqlCmd.ExecuteNonQuery();
hookUp.Close();
txtStartDate.Text = "";
hrs.Value = "";
TextArea1.Value = "";
}
protected void clearData(object sender, EventArgs e) {
txtStartDate.Text = "";
hrs.Value = "";
TextArea1.Value = "";
}
protected void clearTable(object sender, EventArgs e) {
hookUp = new SqlConnection("Server=localhost\\SqlExpress;Database=test1;" + "Integrated Security=True");
strInsert = "DELETE FROM Overtime";
sqlCmd = new SqlCommand(strInsert, hookUp);
hookUp.Open();
sqlCmd.ExecuteNonQuery();
hookUp.Close();
}
protected void CheckString(object sender, ServerValidateEventArgs e) {
//MessageBox.Show("Function called");
string stringToValidate;
stringToValidate = txtStartDate.Text;
if (stringToValidate == "") {
e.IsValid = false;
}


}

}

Couple things that may make life easier ...

  • Use ValidationGroup names. Then you can validate groups or individual inputs
  • Don't use inline SQL. Write a view or procedure to do the work, then call the procedure. Big security no no. Inline SQL opens you up to SQL injection.
  • For dates, use the RegEx validators and use the prebuilt expressions that are included. Much easier to work with.
  • Learn RegEx ... not hard for the basic stuff, and very powerful
  • Learn how to use Enterprise Manager. This will make your SQL calls super easy to code, and it's easy to setup and use.

thanks guys, I did it eventually and not used the custom validator (as I couldn't get that to work), I managed to do everything with the range validator and the required field

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.