Reputation: 912
I'm trying to apply some client side validations using Javascript which is working fine,
But even when validation returns false the form goes to server side methods ex. btnSubmit_Click()
It may be happening because I'm calling the JavaScript function on btnSubmit
like below:
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" OnClientClick="Javascript:validate()"/>
I wants to check whether every Textbox values are valid or not, Then if all are valid then perform server side call i.e btnSubmit_Click()
event else remain on same form until all values of TextBoxes are valid.
How to achieve this on single button?
Below is complete JavaScript
function and aspx
code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function validate() {
var summary = "";
summary += isvalidFirstname();
summary += isvalidEmail();
summary += isvalidphoneno();
if (summary != "") {
alert(summary);
return false;
}
else {
return true;
}
}
function isvalidphoneno() {
var uid;
var temp = document.getElementById("<%=txtPhone.ClientID %>");
uid = temp.value;
var re;
re = /^[0-9]d(10)/;
var digits = /\d(10)/;
if (uid == "") {
return ("Please enter phoneno" + "\n");
}
else if (re.test(uid)) {
return "";
}
else {
return ("Phoneno should be digits only" + "\n");
}
}
function isvalidFirstname() {
var uid;
var temp = document.getElementById("<%=txtName.ClientID %>");
uid = temp.value;
var re = /^[a-zA-Z ]+$/
if (uid == "") {
return ("Please enter firstname" + "\n");
}
else if (re.test(uid)) {
return "";
}
else {
return ("FirstName accepts Characters and spaces only" + "\n");
}
}
function isvalidEmail() {
var uid;
var temp = document.getElementById("<%=txtEmail.ClientID %>");
uid = temp.value;
var re = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
if (uid == "") {
return ("Please Enter Email" + "\n");
}
else if (re.test(uid)) {
return "";
}
else {
return ("Email should be in the form ex:[email protected]" + "\n");
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset>
<legend>Employee Registration Form</legend>
<table>
<tr>
<td>Name: </td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Phone Number: </td>
<td>
<asp:TextBox ID="txtPhone" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Email Id: </td>
<td>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Address: </td>
<td>
<asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" OnClientClick="Javascript:validate()"/></td>
</tr>
</table>
</fieldset>
</div>
</form>
</body>
</html>
Upvotes: 1
Views: 1861
Reputation: 73751
You must return the value of the validate
function in OnClientClick
:
OnClientClick="return validate();"
Upvotes: 4