Introduction
In this snippet we will see how to call a java script client side validation function before server side method execution.
Below code shows calling a onClientClick method before onClick methods of button. The methods, onClientClick is calling a client side validation function where as onClick is calling server side code. In the validation function we are checking whether the textbox value is empty or not. If the value is empty then it returns false and will not execute any server side code. If the textbox has value then it returns true and server side event(btnSubmit_Click) will be executed.
DesignerPage(.aspx)
<head>
<script type="text/javascript">
function validate() {
//if validation sucess return true otherwise return false.
if (document.getElementById("txtSample").value != "") {
return true;
}
alert('Enter a value');
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter a value:<asp:TextBox ID="txtSample" runat="server"></asp:TextBox><br />
<asp:Button ID="btnSubmit" runat="server" Text="Click Me" OnClientClick="javascript:return validate();"
OnClick="btnSubmit_Click" />
</div>
</form>
</body>
</html>
CodeBehind(.aspx.cs)
protected void btnSubmit_Click(object sender, EventArgs e)
{
Response.Write("The textbox value is " + txtSample.Text);
}
Output:
If textbox value is empty then validation returns false then alert('Enter a value') comes and server side code will not be executed.
If textbox has value(DotNetMirror) then validation function returns true and server side code executes. and output is "The textbox value is DotNetMirror".