How to code Javascript for a Command Button

I have been scouring the Internet for examples on linking Javascript code to a command button. Here is the scenario:
The business rules for the form I have created are complex. The screen has textboxes for SSN, Last Name, First Name & Middle Name/Middle Initial, and finally, DOB. I need to code the "Submit" button on my form to execute client-side validation to ensure the following scenarios:
No fields are blank. <-- I can probably leave this as server side.
If the SSN is entered, then the name fields and DOB cannot be entered
If the First Name Middle Name is populated, then the Last Name cannot be blank
If the DOB is entered, the SSN cannot be populated
In the event the above rules pass validation, then the form will build the necessary SQL to perform a data lookup and populate a Datagrid on a new form.
As I stated, I can't find examples that show how to execute Javascript from a Command Button.
Thanks,
Finkle
[991 byte] By [Mr.Finkle] at [2008-1-21]
# 1
The best way would probably be to use the Validator controls that are part of ASP.NET and will automatically generate the javascript for you.

You would use RequiredFieldValidator's and RegularExpressionValidator's for this form.

The upside is that these will produce client-side javascript and can be used to double-check on the server as well.

If you would like to see some of these in action, look here: http://consultutah.com/post.aspx

consultutah at 2007-10-6 > top of Msdn Tech,Feedback for forums and MSDN websites,Off-Topic Posts (Do Not Post Here)...
# 2
consultutah wrote:
The best way would probably be to use the Validator controls that are part of ASP.NET and will automatically generate the javascript for you.

You would use RequiredFieldValidator's and RegularExpressionValidator's for this form.

The upside is that these will produce client-side javascript and can be used to double-check on the server as well.

If you would like to see some of these in action, look here: http://consultutah.com/post.aspx


I don't think you understand my question. We have complex business rules. SSN and name cannot both be entered. Neither can the SSN and the DOB. I have to have some type of validation in place that will check the entire form, client side, and note any validation errors. I can't make any one particular field mandatory.
Mr.Finkle at 2007-10-6 > top of Msdn Tech,Feedback for forums and MSDN websites,Off-Topic Posts (Do Not Post Here)...
# 3

Sorry about that. I read your original message a little too quickly. So, what you are looking for is more like this: http://consultutah.com/samples/hookevents.aspx

The magic is in the javascript that you can see if you view the page source in IE. Note that even though you check rules on the client-side, you should re-check them on the server-side as well. This code will not work if they have javascript disabled or are on a down-level browser. It does work in IE 6 and FireFox 1.5.

Here is the full page source:



<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

void Page_Load(object sender, EventArgs e)
{
}

void SubmitButton_Clicked(object sender, EventArgs e)
{
// You will want to verify that all of the client-side
// rules here on the server-side too. You don't want them
// script kiddies showing you up... ;-)

this.Response.Write("Form Submitted");
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Please enter one or the other:</td>
</tr>
<tr>
<td>SSN:</td>
<td>
<asp:TextBox ID="SsnField" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>DOB:</td>
<td>
<asp:TextBox ID="DobField" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>
<asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Clicked" />
</td>
</tr>
</table>

<script language='javascript'><!--
function hookIt() {
var btn = document.getElementById('SubmitButton');
var oldFunc = btn.onclick;

btn.onclick = function() {
var ssn = document.getElementById('SsnField');
var dob = document.getElementById('DobField');

if (ssn.value.length > 0 && dob.value.length > 0) {
alert('If you enter the SSN, you cannot enter the DOB');
return false;
}
else if (ssn.value.length == 0 && dob.value.length == 0) {
alert('You must enter either the SSN of the DOB');
return false;
}

if (oldFunc != null) {
return oldFunc();
}
return true;
}
}
hookIt();
--></script>
</div>
</form>
</body>
</html>


consultutah at 2007-10-6 > top of Msdn Tech,Feedback for forums and MSDN websites,Off-Topic Posts (Do Not Post Here)...
# 4

I like your example, but it does not appear to work in ASP.Net. Every time I click on the Submit button I have coded in my code, nothing happens.

This is an in-house tool, so I'm not too worried about people trying to hack the system; however, I will incorporate server-side validation as a precaution. I am in the learning stages of Javascript and .Net programming, having come from a background of Cobol and Adabas Natural for the past 10 years.

Here is a copy of the HTML of my program:

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="Privacy.WebForm1" debug="True"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>Airmen Certification System</title>
<meta content="True" name="vs_showGrid">
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
<script language="JavaScript">
//Define the Global Variables here
var curr_Date = new Date()
var str_Date = ((curr_Date.getMonth() + 1) + '/' + (curr_Date.getDate()) + '/' + (curr_Date.getFullYear()))
var s_Date = ((curr_Date.getMonth() + 1) + (curr_Date.getDate()) + (curr_Date.getFullYear()))
var dtCh="/"
var minYear=1850
var chk_Date
var f_date
//End Definition of Global Variables
function isInteger(s){
var i;
for (i = 0; i < s.length; i++){
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}

function stripCharsInBag(s, bag){
var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++){
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}

function daysInFebruary (year){
// February has 29 days in any year evenly divisible by four,
// EXCEPT for centurial years which are not also divisible by 400.
return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
for (var i = 1; i <= n; i++) {
thisIdea = 31
if (i==4 || i==6 || i==9 || i==11) {thisIdea = 30}
if (i==2) {thisIdea = 29}
}
return this
}

function isDate(dtStr){
var daysInMonth = DaysArray(12)
var pos1=dtStr.indexOf(dtCh)
var pos2=dtStr.indexOf(dtCh,pos1+1)
var strMonth=dtStr.substring(0,pos1)
var strDay=dtStr.substring(pos1+1,pos2)
var strYear=dtStr.substring(pos2+1)
strYr=strYear
if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
for (var i = 1; i <= 3; i++) {
if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
}
month=parseInt(strMonth)
day=parseInt(strDay)
year=parseInt(strYr)
if (strMonth.length<1 || month<1 || month>12){
alert("Please enter a valid month")
return false
}
if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
alert("Please enter a valid day")
return false
}
// Any two digit year has the century 19 appended to the front per CAIS standards
if (strYear.length == 2){
var x = 19
strYear=(x) + (strYear)
return true
} else if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
return false
}
//The following calls a function that uses two parameters
if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
alert("Please enter a valid date")
return false
}
chk_Date = strMonth + "/" + strDay + "/" + strYear
if (chk_Date > str_Date){
alert("Date cannot be greater than the current date")
return false
}
if (document.Form1.s_Type.value == "DOB")
if ((curr_Date.getFullYear() - strYear < 12)){
alert("DOB must compute to 12 or Greater" + strYear)
return false
}
return true
}

//If the DOB is passed, then the isDate function is called once. If a 'From' and 'Thru' date
//scenario is used, then the function exectutes successively to insure both dates are validated
//and passed into the 'from_Date' and 'thru_Date' parameters.
function val_DateFrom(oSrc, args){
args.Value = (document.Form1.txtFromMM.value) + '/' + (document.Form1.txtFromDD.value) + '/' + (document.Form1.txtFromYY.value)
if (isDate(args.Value)==false){
args.IsValid = false
}else{
f_Date = chk_Date
document.Form1.thru_Date.value = f_Date
}
}

function val_DateThru(oSrc, args){
if (document.Form1.txtFromMM.value == "" || document.Form1.txtFromDD.value == "" || document.Form1.txtFromYY.value == "" ){
alert("'From' Date cannot contain blank values")
args.IsValid = false
}else{
args.Value = (document.Form1.txtThruMM.value) + '/' + (document.Form1.txtThruDD.value) + '/' + (document.Form1.txtThruYY.value)
if (isDate(args.Value)==false){
args.IsValid = false
}else{
var t_Date = chk_Date
if (f_Date > t_Date){
alert("'From' Date cannot be greater than 'Thru' Date")
args.IsValid = false
}else{
document.Form1.thru_Date.value = t_Date
}
}
}
}
function isAlphaName(oSrc, args){
var newName = args.Value.length
var validChars="-' "
var search
for (var i=0; i!=newName;i++){
aChar=args.Value.substring(i,i+1)
aChar=aChar.toUpperCase()
search=validChars.indexOf(aChar)
if (search == -1 && (aChar < "A" ||aChar > "Z")){
args.IsValid = false
}
}
}
</script>
</HEAD>
<body ms_positioning="GridLayout">
<form id="Form1" name="Form1" method="post" runat="server">
<asp:button id="btnClear" style="Z-INDEX: 128; LEFT: 632px; POSITION: absolute; TOP: 96px" runat="server"
Text="Reset" Visible="False" ToolTip="Clear All Text fields" Width="62px"></asp:button><asp:customvalidator id="CustomValidator1" style="Z-INDEX: 130; LEFT: 168px; POSITION: absolute; TOP: 112px"
runat="server" ErrorMessage="Error Detected" ControlToValidate="txtSSN" ClientValidationFunction="MyClientValidation"></asp:customvalidator><asp:customvalidator id="valThruDate" style="Z-INDEX: 129; LEFT: 488px; POSITION: absolute; TOP: 384px"
runat="server" ErrorMessage="Invalid Date or Format" ControlToValidate="txtThruYY" ClientValidationFunction="val_DateThru"></asp:customvalidator><input
type=hidden value="<%=date_Type%>" name=s_Type> <input
type=hidden value="<%=from_Date%>" name=from_Date><input
type=hidden value="<%=thru_Date%>" name=thru_Date>
<asp:customvalidator id="valLastName" style="Z-INDEX: 115; LEFT: 528px; POSITION: absolute; TOP: 248px"
Width="336px" ErrorMessage="Last Name Contains Invalid Characters" ControlToValidate="txtLastName"
ClientValidationFunction="isAlphaName" ForeColor="Blue" Runat="server"></asp:customvalidator><asp:textbox id="txtThruDD" style="Z-INDEX: 127; LEFT: 520px; POSITION: absolute; TOP: 347px"
runat="server" Visible="False" ToolTip="1 Digit or 2 Digit Date (i.e. 3, 06, 25)" Width="26px" Height="24"></asp:textbox><asp:textbox id="txtThruMM" style="Z-INDEX: 126; LEFT: 480px; POSITION: absolute; TOP: 347px"
runat="server" Visible="False" ToolTip="1 Digit or 2 Digit Month (i.e. 1, 04, 10)" Width="26px" Height="24"></asp:textbox><asp:textbox id="txtFromDD" style="Z-INDEX: 125; LEFT: 352px; POSITION: absolute; TOP: 347px"
runat="server" Visible="False" ToolTip="1 Digit or 2 Digit Date (i.e. 3, 06, 25)" Width="26" Height="24" MaxLength="2"></asp:textbox><asp:textbox id="txtFromMM" style="Z-INDEX: 124; LEFT: 312px; POSITION: absolute; TOP: 347px"
runat="server" Visible="False" ToolTip="1 Digit or 2 Digit Month (i.e. 1, 04, 10)" Width="26" Height="24" MaxLength="2"></asp:textbox><asp:label id="lblSSNFormat" style="Z-INDEX: 123; LEFT: 312px; POSITION: absolute; TOP: 216px"
runat="server" Visible="False">(i.e. 333224444)</asp:label><asp:customvalidator id="valFromDate" style="Z-INDEX: 122; LEFT: 304px; POSITION: absolute; TOP: 384px"
runat="server" ErrorMessage="Invalid Date or Format" ControlToValidate="txtFromYY" ClientValidationFunction="val_DateFrom"></asp:customvalidator><asp:regularexpressionvalidator id="valSSN" style="Z-INDEX: 121; LEFT: 528px; POSITION: absolute; TOP: 192px" runat="server"
Width="198px" ErrorMessage="SSN Must be 9 Numeric Digits" ControlToValidate="txtSSN" ForeColor="Blue" ValidationExpression="\d{9}"></asp:regularexpressionvalidator><asp:textbox id="txtSSN" style="Z-INDEX: 120; LEFT: 312px; POSITION: absolute; TOP: 187px" runat="server"
Visible="False" ToolTip="9-Digits, No Dashes (e.g. 333224444)" Width="89" MaxLength="9" AutoPostBack="True" Wrap="False"></asp:textbox><asp:textbox id="txtThruYY" style="Z-INDEX: 119; LEFT: 560px; POSITION: absolute; TOP: 347px"
runat="server" Visible="False" ToolTip="2 Digit Year or 4 Digit Year (i.e. 47, 1989, 2004)" Width="35px" Height="24"></asp:textbox><asp:textbox id="txtFromYY" style="Z-INDEX: 118; LEFT: 392px; POSITION: absolute; TOP: 347px"
runat="server" Visible="False" ToolTip="2 Digit Year or 4 Digit Year (i.e. 47, 1989, 2004)" Width="35" Height="24" MaxLength="4"></asp:textbox><asp:customvalidator id="valFMName" style="Z-INDEX: 117; LEFT: 528px; POSITION: absolute; TOP: 280px"
runat="server" Width="240px" ErrorMessage="CustomValidator" ControlToValidate="txtFMName" ClientValidationFunction="isAlphaName" ForeColor="Blue">FM Name Contains Invalid Characters</asp:customvalidator><asp:textbox id="txtLastName" style="Z-INDEX: 116; LEFT: 312px; POSITION: absolute; TOP: 248px"
Visible="False" ToolTip="O'Dell, Jackson-Smith, Thomas Clark, Anderson" Width="184px" Runat="server" MaxLength="25" text=""></asp:textbox><asp:label id="lblError" style="Z-INDEX: 114; LEFT: 216px; POSITION: absolute; TOP: 152px"
runat="server" Visible="False" Width="520px" ForeColor="Blue"></asp:label><asp:button id="btnSearch" style="Z-INDEX: 113; LEFT: 544px; POSITION: absolute; TOP: 96px"
Text="Search" Visible="False" ToolTip="Execute a Search When Values Are Entered" Width="62" Runat="server"></asp:button><asp:textbox id="txtEmployer" style="Z-INDEX: 112; LEFT: 312px; POSITION: absolute; TOP: 312px"
runat="server" Visible="False" Width="248px" MaxLength="35"></asp:textbox><asp:label id="lblEmployer" style="Z-INDEX: 111; LEFT: 216px; POSITION: absolute; TOP: 312px"
runat="server" Visible="False">Employer</asp:label><asp:label id="lblThru" style="Z-INDEX: 110; LEFT: 440px; POSITION: absolute; TOP: 352px" runat="server"
Visible="False">thru</asp:label><asp:textbox id="txtFMName" style="Z-INDEX: 109; LEFT: 312px; POSITION: absolute; TOP: 280px"
runat="server" Visible="False" ToolTip="John, Robert James, Wayne A" Width="184px" MaxLength="25"></asp:textbox><asp:label id="lblLastName" style="Z-INDEX: 108; LEFT: 216px; POSITION: absolute; TOP: 248px"
runat="server" Visible="False">Last Name</asp:label><asp:label id="lblFMName" style="Z-INDEX: 107; LEFT: 216px; POSITION: absolute; TOP: 280px"
runat="server" Visible="False">FM Name</asp:label><asp:label id="lblDOB" style="Z-INDEX: 106; LEFT: 216px; POSITION: absolute; TOP: 352px" runat="server"
Visible="False">DOB</asp:label><asp:label id="lblSSN" style="Z-INDEX: 105; LEFT: 216px; POSITION: absolute; TOP: 192px" runat="server"
Visible="False">SSN</asp:label><asp:label id="lblSearch" style="Z-INDEX: 104; LEFT: 320px; POSITION: absolute; TOP: 96px"
runat="server">Search Criteria</asp:label><asp:label id="lblHeader2" style="Z-INDEX: 103; LEFT: 312px; POSITION: absolute; TOP: 56px"
runat="server" ForeColor="Black" Font-Bold="True">PRIVACY ACT FILE INQUIRY</asp:label><asp:label id="lblHeader1" style="Z-INDEX: 102; LEFT: 288px; POSITION: absolute; TOP: 16px"
runat="server" Width="274px" ForeColor="Black" Font-Bold="True">AIRMEN CERTIFICATION SYSTEM</asp:label><asp:dropdownlist id="lstSelectionCriteria" style="Z-INDEX: 101; LEFT: 424px; POSITION: absolute; TOP: 96px"
tabIndex="1" runat="server" AutoPostBack="True">
<asp:ListItem Value="Select">[Select]</asp:ListItem>
<asp:ListItem Value="Airman">Airman</asp:ListItem>
<asp:ListItem Value="Requester">Requester</asp:ListItem>
<asp:ListItem Value="UserID">UserID</asp:ListItem>
</asp:dropdownlist></form>
<script language="javascript">
//If 'Airman' is selected, the Date of Birth calculation must be set; otherwise, the
//current year is used as the maximum value that can be used.
if (document.Form1.s_Type.value == "DOB")
var maxYear=(curr_Date.getFullYear() - 12)
else {
var maxYear=(curr_Date.getFullYear())
}
</script>
</body>
</HTML>

Mr.Finkle at 2007-10-6 > top of Msdn Tech,Feedback for forums and MSDN websites,Off-Topic Posts (Do Not Post Here)...
# 5

I've built numerous web forms which required similar constraints. The way I handled them is by not implementing .Net functionality at all. Rather, I write JavaScript functionality and prevent the OnSubmit event from occurring if validation fails.

Something like this:

<form id="frmSubmit" runat="Server">
<input type="submit" id="btnSubmit" runat="Server" OnClick="return PerformValidation();" />
<script language="JavaScript">
<!--
function PerformValidation() {
var blnSuccessful = false;

// Validation here ....... business rules checked.....
if (true)
blnSuccessful = true;
else
blnSuccessful = false;

return blnSuccessful;
}
//-->
</script>
</form>

That way, if validation fails, the form doesn't post back.

DotNetFun at 2007-10-6 > top of Msdn Tech,Feedback for forums and MSDN websites,Off-Topic Posts (Do Not Post Here)...
# 6
Well, I played with the form and discovered that even if the Submit Button (or in my case the Search Button) is depressed, the validation takes affect and won't process any further.
My newest problem with with the date validation. As you can see, once my val_FromDate function completes there is a variable called chk_Date that has the validated and properly formatted date. I need to pass that value *BACK* to .Net to use in an SQL lookup. For example, when the val_FromDate function receives 011299 the return date will be 1/12/1999, and I need 1/12/1999 to be sent back to my ASP.Net form for my SQL query. I have tried using the following in my valDateFrom_ServerValidate:
If args.IsValid = True Then
from_Date = args.Value
End If
Unfortunately, it appears that args.Value will only contain what was sent to Javascript for validating, which is '99'. I have tried to over ride that on the Javascript side to no avail. I forsee the need for this ability in many future projects.
Mr.Finkle at 2007-10-6 > top of Msdn Tech,Feedback for forums and MSDN websites,Off-Topic Posts (Do Not Post Here)...
# 7

RE: I need 1/12/1999 to be sent back to my ASP.Net form for my SQL query

Store it in a hidden field before submitting the form back to ASP.NET.

DotNetFun at 2007-10-6 > top of Msdn Tech,Feedback for forums and MSDN websites,Off-Topic Posts (Do Not Post Here)...
# 8
No, I want 1/12/1999 sent to my form BACK from Javascript editing.
Mr.Finkle at 2007-10-6 > top of Msdn Tech,Feedback for forums and MSDN websites,Off-Topic Posts (Do Not Post Here)...
# 9
Yes, this is possible by storing it in a hidden INPUT control and POSTing it back to .Net.
DotNetFun at 2007-10-6 > top of Msdn Tech,Feedback for forums and MSDN websites,Off-Topic Posts (Do Not Post Here)...
# 10
The date is being passed via a hidden field to Javascript. A code example of how to pass 12/31/1999 back to my code behind would more more helpful than saying it can be done.
Mr.Finkle at 2007-10-6 > top of Msdn Tech,Feedback for forums and MSDN websites,Off-Topic Posts (Do Not Post Here)...