You are on page 1of 5

Example- Numeric and Datetime Fields in Database

Page 1 of 5

Step 1:
Create the following database table (You can use any current project)

Table name is ContractEmployee. It has the following fields

Id - Int , PrimaryKey and Identity


ContractEmployeeName varchar(100) NOT NULL
ContractEmployeeCode vachar(100) not null
Salary decimal(16,2) Not Null
DateOfJoining DateTime Not Null
Status varchar(10) Not Null

Step 2:
Create a folder ContractEmployees.Add 3 forms (with MasterPage)
ContractEmployeeList.aspx
NewContractEmployee.aspx
EdiitContractEmployee.aspx

And If you have a Menu in the master page and Link the ContractEmployeeList.aspx from the
Main Menu (preferably as a submenu of Administration)

NOTE: I DON’T MIND YOU COPY-PASTING THE ASPX MARKUP. BUT MAKE SURE YOU
OBSERVE IT PROPERLY.

Step3:
Build the User Interface of NewContractEmployee.aspx. Create the Page Title and the “Back to
Contract Employee List” link and then proceed with the fields.

We need the following

3.1 A TextBox with ID TxtContractEmployeeName. A Required FIeld Validator with that


TextBox. Note that we will not be checking for duplicates for Employee Name. We will
check for duplicates for Employee Code.
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-3">
<label>Contract Employee Name: </label>
<asp:TextBox runat="server" ID="TxtContractEmployeeName"
CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="ReqContractEmployeeName" runat="server"
CssClass="text-danger" ControlToValidate="TxtContractEmployeeName"
Example- Numeric and Datetime Fields in Database
Page 2 of 5

ErrorMessage="Please specify the Contract Employee Name"


Display="Dynamic"></asp:RequiredFieldValidator>
</div>
</div>

3.2 We also need a TextBox,RequiredFieldValidator and a Label for


ContractEmployeeCode as below
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-3">
<label>Contract Employee Code: </label>
<asp:TextBox runat="server" ID="TxtContractEmployeeCode"
CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="ReqContractEmployeeCode" runat="server"
CssClass="text-danger" ControlToValidate="TxtContractEmployeeCode"
ErrorMessage="Please specify the Contract Employee Code"
Display="Dynamic"></asp:RequiredFieldValidator>
<asp:Label runat="server" ID="LblDuplicateContractEmployeeCode"
CssClass="text-danger" Visible="false" Text="A Duplicate Employee Code already exists in the
database"></asp:Label>
</div>
</div>

3.3 For Salary we need a TextBox, a Required Field Validator, One Compare Validator for
data type check and one more validator to check that Salary must be greater than zero.
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-3">
<label>Salary: </label>
<asp:TextBox runat="server" ID="TxtSalary" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="ReqSalary" runat="server" CssClass="text-danger"
ControlToValidate="TxtSalary" ErrorMessage="Please specify the Salary"
Display="Dynamic"></asp:RequiredFieldValidator>
<asp:CompareValidator runat="server" ID="CmpSalary1" CssClass="text-danger"
ControlToValidate="TxtSalary" ErrorMessage="Salary must be numeric" Type="Double"
Operator="DataTypeCheck"></asp:CompareValidator>
<asp:CompareValidator runat="server" ID="CmpSalary2" CssClass="text-danger"
ControlToValidate="TxtSalary" ErrorMessage="Salary must be greater than zero"
Type="Double" Operator="GreaterThan" ValueToCompare="0"></asp:CompareValidator>
</div>
</div>

3.4 For Joining Date, we should have given the user a good way to input date. This can
be done in 3 ways.
Example- Numeric and Datetime Fields in Database
Page 3 of 5

a. Use a Calendar Control . But then we need a button to show the calendar etc… its
a little lengthy
b. We can use the CALENDAREXTENDER from AJAX Toolkit but we havent learnt
AJAX yet.
c. We could use a Compare Validator with Operator as DataTypeCheck and Type as
Date. But this also I found is a little clumsy...Better to stick to server side for Date
Validations
So FOR NOW, we will simply provide a TextBox and expect the user to enter the date in
mm/dd/yyyy format - example: 31/12/2018

We will not use a regular expression validator. We will simply Parse and Check the Date
on Server Side in BtnAdd_Click and show a Error Message if the Format is Incorrect.

See the following Markup CAREFULLY. See that there are two labels which will show
errors from Server Side Checking.
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-3">
<label>Date of Joining (mm/dd/yyyy): </label>
<asp:TextBox runat="server" ID="TxtDateOfJoining"
CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="ReqDateOfJoining" runat="server"
CssClass="text-danger" ControlToValidate="TxtDateOfJoining" ErrorMessage="Please specify
the Date Of Joining" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:Label runat="server" ID="LblInvalidDateFormatError" Visible="false"
CssClass="text-danger" Text="Invalid Date Format"></asp:Label>
<asp:Label runat="server" ID="LblInvalidDateError" Visible="false"
CssClass="text-danger" Text="Joining Date cannot be greater than current date"></asp:Label>
</div>
</div>

3.5 And finally we put the “Add” button.


<div class="row">
<div class="col-xs-12 col-sm-4 col-md-3">
<asp:Button runat="server" ID="BtnAdd" Text="Add this Contract Employee"
CssClass="btn btn-default" OnClick="BtnAdd_Click" />
</div>
</div>

Step 4: Code in Page Load …… NEVER FORGET THIS…..It is small work, but important
from UI Point of View.
if(this.IsPostBack == false)
{
TxtContractEmployeeName.Focus();
Example- Numeric and Datetime Fields in Database
Page 4 of 5

this.Form.DefaultButton = BtnAdd.UniqueID;
}
else
{
LblDuplicateContractEmployeeCode.Visible = false;
LblInvalidDateError.Visible = false;
LblInvalidDateFormatError.Visible = false;
}

Step 5: Server side Validation Code

Strategy: ​We have 3 server side validations.


- To check for Duplicate Employee Code
- To Check Date Format is Correct Or Not
- To Check If the Joining Date is Greater than the Current Date.

In our earlier example, we always displayed the error label and immediately returned in the if()
check for an error. That was because earlier we had only one validation. If we return in each if,
only one error will be shown at a time. So we use a different strategy. See the code below,

Interesting observation is also that the check for joining date greater than current date
must be written in the else part of format check. Doesn’t take a genius to figure that..does
it??

if (this.IsValid == true)//VERY IMportant to ensure validation controls were checked properly


{
//First we assume ALL IS WELL
bool ALLOK = true;
SqlConnection ObjConnection = new
SqlConnection(ConfigurationManager.ConnectionStrings["TestOCRM"].ConnectionString);
ObjConnection.Open();
string strsql = "select count(*) from ContractEmployee where ContractEmployeeCode ='"
+ TxtContractEmployeeCode.Text.Replace("'", "''") + "'";
SqlCommand ObjCommand = new SqlCommand(strsql, ObjConnection);
if ((int)ObjCommand.ExecuteScalar() > 0)
{
//If Duplicate is found, turn the error label visible. DO NOT RETURN. Just Mark
ALLOK to false. We will return only after all CHECKS
//EVEN IF ONE CHECK IS NOT CORRECT ALLOK WILL BE FALSE IN THE END. IF
IT IS FALSE WE RETURN ELSE WE ADD
LblDuplicateContractEmployeeCode.Visible = true;
ALLOK = false;
Example- Numeric and Datetime Fields in Database
Page 5 of 5

}
ObjCommand.Dispose();
ObjConnection.Dispose();
DateTime ObjJoiningDate = DateTime.MinValue;//DateTime Object in C# cannot be set
to null, but MINVAL is generally treated as null
if (DateTime.TryParse(TxtDateOfJoining.Text, out ObjJoiningDate) == false)
{
// TryParse will return false...it will not crash unlike .Parse().However if it succeeds in
Parsing, it will put the extracted date in ObjJoiningDate
LblInvalidDateFormatError.Visible = true;
ALLOK = false;
}
else
{
if (ObjJoiningDate > DateTime.Now)
LblInvalidDateError.Visible = false;
ALLOK = false;

if (ALLOK == false)
return;
else //doesnt matter if we dont write else because it will return and stop execution
anyways
{
Response.Write("Will add.");
// WILL SEND YOU THE ACTUAL ADDING CODE LATER. FOR NOW JUST
UNDERSTAND HOW MULTIPLE VALIDATIONS ON SERVER SIDE MUST BE DONE
}
}// BRACKET FOR CLOSING this.IsValid.

You might also like