Using C# with ASP.NET on an Intranet website. I've got multiple "Admin" pages where I'm checking fields to make sure a date is present, checking fields to make sure the Username is present and filling in those fields if they were left blank. On all of these pages, there exists fields with identical names. The block of code I'm using in the code-behind is below:
//If the User fields are empty, set them to the current user
string ActiveUser = System.Web.HttpContext.Current.User.Identity.Name;
string LoginID = ActiveUser.Right(6);
var txtLoadedBy_chk = string.IsNullOrEmpty(str5);
if ((txtLoadedBy_chk == true))
{
str5 = LoginID;
}
var txtUpdatedBy_chk = string.IsNullOrEmpty(str7);
if ((txtUpdatedBy_chk == true))
{
str7 = LoginID;
}
var txtFlgUpdatedBy_chk = string.IsNullOrEmpty(str9);
if ((txtFlgUpdatedBy_chk == true))
{
str9 = LoginID;
}
// If the date fields are NULL, set them to today's date
var txtLoadedOn_chk2 = string.IsNullOrEmpty(str6);
if ((txtLoadedOn_chk2 == true))
{
str6 = DateTime.Today.ToString();
}
var txtUpdatedOn_chk2 = string.IsNullOrEmpty(str8);
if ((txtUpdatedOn_chk2 == true))
{
str8 = DateTime.Today.ToString();
}
var txtFlgUpdatedOn_chk2 = string.IsNullOrEmpty(str10);
if ((txtFlgUpdatedOn_chk2 == true))
{
str10 = DateTime.Today.ToString();
}
// Check to make sure the dates entered are valid. If not, let the user know and
// then exit out of the code so the record is not saved
var txtLoadedOn_chk = DateTimeHelpers.IsValidSqlDateTimeNative(str6);
var txtUpdatedOn_chk = DateTimeHelpers.IsValidSqlDateTimeNative(str8);
var txtFlgUpdatedOn_chk = DateTimeHelpers.IsValidSqlDateTimeNative(str10);
if ((txtLoadedOn_chk == false) || (txtUpdatedOn_chk == false) || (txtFlgUpdatedOn_chk == false))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "ch", "<script>alert('WARNING !! One of your date fields is invalid')</script>");
return;
}
I'm thinking that since I do the EXACT same checks on all of these forms, I should be able to put this block of code somewhere and just reference it, instead of putting it in every form. How would I go about doing that? If I put it in a separate page or CS file, how will it know which form is calling it so it reads the proper fields? If you can provide some sample code, that would be a huge help. TIA!
Oh, and DateTimeHelpers is a class I created, in case you're wondering.
EDIT: I just want to be clear on something; this code is in the code-behind and is called when the user presses the "Save" button. It's just verifying the data before it tries to write it to the SQL Server table.