Perform Validations using JavaScript:
Validating the web forms is the most important and common task in developing applications. Validating the page without allowing the user to post the page to server enhances the user experience. In this section, we will see how to validate the web form by using client side JavaScript.
Access the ASP.NET Server Controls using JavaScript
You can access the ASP.NET server controls by using the following script:
var employeeid = document.getElementById('<%= TextBox1.ClientID %>');
Similarly, you can access all other controls in the form.
Make textbox accept only digits
The following function is used to make a text box to accept only digits.
function isNumberKey(evt) {
if (charCode = evt.which) {
charCode = evt.which;
}
else {
charCode = evt.keyCode;
}
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
else {
return true;
}
}
Validate the emailid
Emaild
can be validated by checking the position of ‘@’ and ‘.’ characters in the
emailid
as follows:
var atpos = emailid.value.indexOf("@");
var dotpos = emailid.value.lastIndexOf(".");
if ((inputDOJ.value == "") || (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= inputDOJ.length))
{
lbl3.innerHTML = "Not a valid e-mail address";
flag = 1;
}
Check if the date is greater than today:
You check the entered date with the date object of the JavaScript as shown below:
var DOJ = new Date(inputDOJ.value);
var todaydate = new Date();
var month = todaydate.getMonth() + 1;
var today = new Date(month + '/' + todaydate.getDate() + '/' + todaydate.getFullYear());
if ((inputDOJ.value == "") || (DOJ < today))
{
lbl2.innerHTML = "Date should be greater than today"
flag = 1;
}
Check the values to be distinct
You can check if the entered values in the two fields are distinct by using the following code:
if (reportingmanger.value == employeeid.value)
{
lbl6.innerHTML = "Reporting MangerID should not be same as EmployeeID";
flag = 1;
}
Check if the values in the fields are blank
Javascript can be used to make the fields as mandatory by using the following code snippet:
if (reportingmanger.value == "")
{
lbl6.innerHTML = "ReportingManagerID cannot be blank";
flag = 1;
}
Check the length of employeeid
Length of the value entered in the field can be checked by using '
length
' property.
if ((employeeid.value == "" ) || (employeeid.value.length != 4))
{
lbl1.innerHTML = "Please Enter Valid 4 digit EmployeeID";
flag = 1;
}