Prevent page being post back if javascript validations fails - c#

I've following asp text box:
<asp:TextBox ID="txtPasswrod" runat="server"></asp:TextBox>
below this text box I've error message label, which is initially hidden until the js validation of the text box fails:
<label id="errorMsg" for="pwd" style="display:none">error</label >
Following is the js for textbox validation:
function validation()
{
var pwd = document.getElementById("txtPasswrod").value;
if (pwd == null || pwd == "")
{
document.getElementById("error").style.display = 'block';
return false;
}
}
Following is the asp button, whose OnClientClick event I am calling validation() function:
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" OnClientClick="validation()"/>
The validation is working all fine, but the problem is that when text box is empty and my validation fails the js should prevent page from being post back, but the js allowing the page being post back and my validation jst becoming useless.
Please tell me how to prevent page postback on failing the js validation.

Modify validation() to return validation(), This will stop page to post if function returns false.
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" OnClientClick="return validation();"/>

You need a slight change in your JS script. You need to add .ClientID as the control you are specifying is a server control. Or if you are on .net 4.0 , you can use ClientIDMode= "Static" to access the control as you are using in your code.
function validation() {
var pwd = document.getElementById('<%=txtPasswrod.ClientID').value;
if (pwd == null || pwd == "")
{
document.getElementById("errorMsg").style.display = 'block';
return false;
}
}
Now call the validation method something like this:
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" OnClientClick="return validation();"/>

Related

Obtaining control Id through javascript in asp.net

I have a scenario in my asp.net application where when enter button is keyed in any of the multiline textboxs, I need to add a particular length to the existing length and show it in another control. I have written a generic javascript function to handle key-in in "pnlEnglish" panel. I can find out "Enter key" key up by checking "e.keycode ==13" , However would it be possible to know from which control I am firing the event??. I am trying to avoid adding events to text box since, I have to handle it for too many. Is there any better solution to achieve this??
<asp:Panel ID="pnlEnglish" runat="server">
<asp:TextBox ID="txtPlot" runat="server" Rows="5" TextMode="MultiLine" Width="350px" TabIndex="12"></asp:TextBox>
<asp:TextBox ID="txtLegacyPlot" runat="server" Rows="5" TextMode="MultiLine" Width="350px"TabIndex="12"></asp:TextBox>
</asp:Panel>
Javascript is as below
$('#<%=pnlEnglish.ClientID%> input:text,#<%=pnlEnglish.ClientID%> textarea').keyup(function (e) {
if (e.keyCode == 13) {
//Need to identify the control for which I shall add the length
}
var txtLenPlot = $('#<%=txtPlot.ClientID%>').val().length;
var txtLenLegacyPlot = $('#<%=txtLegacyPlot.ClientID%>').val().length;
//The below function shows the length in length displaying control
update_chars_left(500, $('#<%=txtLengthPlot.ClientID %>'), txtLenPlot);
update_chars_left(205, $('#<%=txtLengthLegacyPlot.ClientID %>'), txtLenLegacyPlot);
});
In side key up function you can get id of textbox in which enter key is pressed as below
$('#<%=pnlEnglish.ClientID%> input:text,#<%=pnlEnglish.ClientID%> textarea').keyup(function (e) {
if (e.keyCode == 13) {
var currTextboxId = $(this).attr('id');
//Your Code
});

onClick and onClientClick event used together. Does not Work in Internet Explorer

Java script code:
<script language="javascript" type="text/javascript">
function validateLoginForm() {
if (document.getElementById("<%=txtTitle.ClientID%>").value == "") {
alert("Please Enter Title");
txtTitle.focus();
return false;
}
}
Button Code
<asp:Button ID="btnPost" UseSubmitBehavior="false" Text="Post" OnClientClick="javascript:validateLoginForm();" runat="server" OnClick="btnPost_Click" />
This code is not working on internet explorer but works fine in firefox
even though the javascript returns false in onClientClick event
the onClick event is still getting called
Please Help...!!!
It can be solved using
<asp:Button ID="btnPost" UseSubmitBehavior="false" Text="Post" OnClientClick="return validateLoginForm();" runat="server" OnClick="btnPost_Click" />
Replace your Java script function with this
function validateLoginForm() {
if (document.getElementById("<%=txtTitle.ClientID%>").value == "") {
alert("Please Enter Title");
txtTitle.focus();
return false;
}
else
return true;
}
And you OnClientClick attribute with this
OnClientClick="javascript:return validateLoginForm();"

How to call a clientside script function first and then call a server side button click event?

Here i am trying to do a email validation for a textbox using jquery and am calling that function on onclientclick and i have a button click event too.But the button click event is firing before the javascript function.I need to validate the textbox before firing the button click event.Here is my code
$(document).ready(function () {
$("#MainContent_txtEmail").blur(function () {
ValidateEmail();
});
function ValidateEmail()
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddress = $("#MainContent_txtEmail").val();
if (!emailReg.test(emailaddress)) {
$("#emailspan").html('<font color="red" size=2px;>Please enter valid Email address</font>');
return false;
}
else {
$("#emailspan").html('<font color="red"></font>');
return true;
}
}
});
and
<asp:TextBox ID="txtEmail" name="txtEmail" runat="server" CausesValidation="false" TextMode="Email">
</asp:TextBox><span id="emailspan" value="0"></span>
<asp:Button ID="btnsubmit" CssClass="btn pdf-submit" runat="server" Text="SEND" OnClientClick="return ValidateEmail();" OnClick="btnsubmit_Click"/>
and my event
protected void btnsubmit_Click(object sender, EventArgs e)
{
SendSmtpEmail(txtEmail.Text, "noreply#a.net", "test", "test-template");
}
Any suggestion??
hey In your code ::
`$("#MainContent_txtEmail").blur(function ()
why you are calling the function you may have to change that in to
$("#txtEmail").blur(function ()`
this will work I guess !!
You'll want to remove the OnClick for btnsubmit
<asp:Button ID="btnsubmit" CssClass="btn pdf-submit" runat="server" Text="SEND" OnClientClick="return ValidateEmailThenSubmit();" />
Then click the btnsubmit manually in code after the validation.
function ValidateEmailThenSubmit()
{
ValidateEmail();
$("#" + <%= btnsubmit.ClientID %>).click();
}
Why use javascript? Just use the asp.net RegularExpressionValidator like so:
<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
More info here http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.regularexpressionvalidator.aspx
The ValidateEmail() method is not visible being declared inside the anonymous method passed as argument to the $.ready() method.
Get the ValidateEmail method outside $(document).ready and it should work.

Unable to get ID for a asp:dropdownlist which gets populated dynamically

I have an unbound list that gets populated.
<asp:DropDownList ID="ddlState" runat="server" style="margin-left: 81px"
onselectedindexchanged="ddlState_SelectedIndexChanged"
CssClass="styled-select">
</asp:DropDownList>
<asp:DropDownList ID="ddlManagerName" runat="server" Height="22px"
style="margin-left: 08px; width:auto;" ></asp:DropDownList>
and a javascript that runs to get the id on a button click
function validateDynamic() {
var getState = document.getElementById('<%=ddlState.ClientID %>').selectedIndex;
var getManager = document.getElementById('<%=ddlManagerName.ClientID %>').selectedIndex;
if(getState == 0)
{
alert("State is a required field !");
}
if(getManager == 0)
{
alert("Manager Name is a required field !");
}
return false;
}
I have tried most using the following from view source
name="ctl00$MainContent$ddlState" id="MainContent_ddlState" both name and id and all i get is object undefined.
Here is the button code that gets calls the function
<asp:Button id="btnSaveTM" runat="server" Text="Add Team Member" class="btn" onmouseover="this.className='btn btnhov'"
onmouseout="this.className='btn'" style=" Height:34px" OnClientClick="validateDynamic();"
onclick="btnSaveTM_Click" UseSubmitBehavior="true" CausesValidation="true" />
and when I debug, I get getState and manager as undefined. Any help is appreciated.
Use this to get the selected value of DropdownList:
var getState = (document.getElementById('<%= ddlState.ClientID %>')
.options[document.getElementById("<%=ddlState.ClientID%>")
.selectedIndex].value)
Have you looked at the sourcecode returned by the server? Does the ID in the script match the ID of the rendered element? Also code nuggets like <%=ddlState.ClientID %> don't work in an external script file. To get them to work you have to embed the script on the page. They only work with .aspx files.
Also you could try to get the element on the console (like Chrome DevTools). If you the right element is returned you can compare it with the line in your script.

Custom validator getting invoked onclick of all controls on the page

i have written a custom validation function to check if a panel is displayed
i want the function to be invoked onclick of NEXT button.
But instead it gets invoked onclick of every button on the page.
Here is the code:
function Validate(sender, args)
{
if (document.getElementById("Panel1").style.display == 'none') {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
and this is the button code onclick of which it should be invoked.
<asp:Button ID="btnNext" runat="server" Text="Next" Font-Bold="True" CssClass="InputButton" OnClick="btnNext_Click" />
<asp:CustomValidator ID="cvValidate" runat="server" ErrorMessage="Panel has no data." ClientValidationFunction="Validate" Display="none" EnableViewState="false"></asp:CustomValidator>
if i set Controltovalidate="btnNext" then it again throws me error.
"btnNext cannot be validated".
You need to hook it to the right element.
document.getElementById("btnNext").onclick = function() {
//Do Your Stuff Here
};
Angela
Hey i did a very simple solution to my problem.
first is the java script code that ws getting invoked onclick of evry button on the page.
function Validate(sender, args)
{
if (document.getElementById("Panel1").style.display == 'none') {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
Then on the Next button:
<asp:Button ID="btnNext" runat="server" Text="Next" Font-Bold="True" CssClass="InputButton" OnClick="btnNext_Click" />
<asp:CustomValidator ID="cvValidate" runat="server" ErrorMessage="Panel has no data." ClientValidationFunction="Validate" Display="none" EnableViewState="false"></asp:CustomValidator>
and for the rest of buttons i did set causesvalidation=false property. with this the function wwas getting invoked only on Next button

Categories