I have the following text box control ;
<asp:TextBox ID="txtAmount" runat="server" AutoPostBack="true" Width="85px" class="validate[ERExpenseTypeDaterequired,custom[float]]"
OnTextChanged="txtAmount_TextChanged" ></asp:TextBox>
Here, if there any value change in the text box , txtAmount_TextChanged will be called because AutoPostBack="true" is there in the control.
So if we put a non numeric value in the textbox, validation error will fire from the attribute Class using Jquery, but this error which pops up as a red box from the textbox wont stays for more than 3 seconds, it vanishes when the page posts back within 3 seconds, This post back is happening just because there is a AutopostBack="true".
I cannot do Autopostback="false" because, I need to do some calculation based on this text box value change on the spot.
If I do Autopostback="false", page will not post back and error message stays for ever, but I cannot do any calculations on "txtAmount_TextChanged" event as this event will never be called on textchcange if Autopostback="false".
So, what I do to prevent this postback, if there is any validation error in this textbox?
function txtAmount_TextChanged(){
//do validations here, Eg: validate if txtAmount is valid amount and "> 0"
return false; //if somethings's wrong, else true
}
You'll need to add a client-side event handler, and return false from it when you don't want a PostBack to happen.
<asp:TextBox onkeydown="return doMyCheck()" ID="txtAmount" runat="server"
AutoPostBack="true" Width="85px" class="validate[ERExpenseTypeDaterequired,custom[float]]"
OnTextChanged="txtAmount_TextChanged"></asp:TextBox>
JavaScript:
function doMyCheck() {
if (// call your jQuery validity check)
return false;
}
Use Input event to check the added text in Textbox using jquery
jQuery('#txtAmount').live('input', function()
{
// do your Validation
// If Valid return True
// If Invalid Return False
}
)
you can use jquery change function
$('#txtbox').change(function() { if(validationfail){return false;} );
you can use keychange event also
$('#txtbox').keyup(function() {
if(validationfail){return false;}
});
Related
Java Script
function outputtax()
{
var tamount = parseFloat(document.getElementById('<%=txtpsubtotal.ClientID%>').value);
var cash = parseFloat(document.getElementById('<%=txtpdiscount.ClientID%>').value);
if (isNaN(tamount) != true && isNaN(cash) != true && isNaN(tax) != true)
{
document.getElementById('<%=txtPtotalamout.ClientID%>').value =
Math.round(parseFloat(document.getElementById('<%=txtpsubtotal.ClientID%>').value)
- parseFloat(document.getElementById('<%=txtpdiscount.ClientID%>').value))
return false;
}
}
<asp:TextBox ID="txtPtotalamout" runat="server" ReadOnly="true">
</asp:TextBox>
.CS
objsupplyPL.totalamount = Convert.ToDouble(txtPtotalamout.Text.ToString());
Value is displaying on the textbox but when i click save button txtptotalamount is getting
null value.If I placed readonly="false" it's working fine.
From http://codecorner.galanter.net/2009/10/09/postback-disabled-textbox/
Let’s say in your ASP.NET application you set a TextBox control’s property ReadOnly to True (or Enabled to False) to prevent user from entering data directly. But you still want to update that text box’s value via client-side JavaScript. Which is happening, the value can be updated. But during postback to the server – surprise, surprise! – the new value doesn’t persist. This is due to security precaution – if the value wasn’t meant to be changed – the change is not allowed. But there is a way around this.
The trick is - to keep ReadOnly = False and Enabled = True and simulate their behavior. Add following line of to your server-side code:
TextBox1.Attributes["onclick"] = "this.blur();"
where TextBox1 is your textbox control. What this line does is adds client-side behavior to the textbox. As soon as user tries to click the textbox, focus immediately gets lost, preventing user from entering data, making the textbox essentially read-only. For further effect you can set the texbox’s background to something like “LightGray” making it appear disabled.
You want to be able to save the result from the "txtPtotalamout" but you don't want it to be editable.
You could just use
<div id="PTotalAmount"><asp:Label id="PTotalAmount" runat="server" /></div>
<asp:HiddenField ID="hPTotalAmount" runat="server" />
To display it, and update the contents of that DIV and the hidden field in the javascript.
Then you could display the total amount in that DIV when you load the form (and populate the hidden field). You could even format the DIV to look like a text box if you wanted.
Very new to ASP.Net development so hope this is not too much of a silly question.
I have a web page (framework 3.5) with a DetailsView control which is bound to sql and reads records via a Stored Procedure. AllowPaging = true on the control because more than one record may be found.
It uses a text box control - value entered by the user - to pass to the SP.
The text box has a Regular expression validation control which highlights when input is invalid.
I am doing as follows:
enter valid data in text box and hit 'enter' - records are found so DetailsView shows me the first record plus numbered paging buttons (correct)
change the value in the textbox to something invalid, and tab out of textbox - validation control highlights the error (correct)
press 'enter' - nothing happens, invalid (correct)
click on one of the numbered paging buttons in the DetailsView - postback occurs. The validation control has not prevented the paging taking place. I would like to prevent any postback/response other than forcing the user to correct the invalid data in the text box.
Am sure there should be an easy way to handle this and have tried various options but not getting there.
Thanks in advance.
Basically here validation doesn't happens when you click on any numbered paging buttons of DetailsView.
Preventing even complete postback requires that page checks for Client side validation. Also
to make the validation occur on server side,call Page.Validate() in PageIndexChanging event of DetailsView. If the page is Not valid prevent the paging from happening.
NOTE I: You can call Page.Validate() inside Page_Load event also. It's not necessary that you should call this event in DetailsView.PageIndexChanging event only.
NOTE II: in case you just want only to prevent paging to occur and don't want to use PagerTemplates, use server side validation. A postback will always happen, although if Page is not Valid, Paging will not occur.
Start by using <PagerTemplates> for paging in DetailsView and set the CausesValidation attribute to true for the pager buttons. The below settings of CommandName & CommandArgument will automatically take care of your Paging. See MSDN.
<pagertemplate>
<asp:LinkButton id="PreviousButton"
text=" Previous_"
CommandName="Page"
CommandArgument="Prev" CausesValidation="true"
runat="Server"/>
<asp:LinkButton id="NextButton"
text="Next_"
CommandName="Page"
CommandArgument="Next" CausesValidation="true"
runat="Server"/>
</pagertemplate>
Markup of DetailsView:
<asp:DetailsView runat="server" ID="EmpDetails"
OnPageIndexChanging="EmpDetails_PageIndexChanging" ... />
Event Handler
protected void EmpDetails_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
{
Page.Validate();
if (!Page.IsValid)
e.Cancel = true;// Prevent the paging
}
The controls in the ASP.NET
<asp:TextBox ID="txtEnd" runat="server" placeholder="12:59"></asp:TextBox>
<asp:RadioButtonList ID="rblTime2" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow">
<asp:ListItem>AM</asp:ListItem>
<asp:ListItem>PM</asp:ListItem>
</asp:RadioButtonList>
CustomValidator
<asp:CustomValidator ID="ValidateStartTime" ControlToValidate="txtEnd" OnServerValidate="ValidateStartTimeFun" runat="server" ErrorMessage="*required"></asp:CustomValidator>
CodeBehind
protected void ValidateStartTimeFun(object source, ServerValidateEventArgs args)
{
try
{ if (txtStart.Text != "" && rblTime.SelectedValue != null )
{ args.IsValid = true; }}
catch (Exception ex)
{ args.IsValid = false; }
}
It doesn't even give me a *required if I change the entire CodeBehind to this;
protected void ValidateStartTimeFun(object source, ServerValidateEventArgs args)
{
args.isValid = false;
}
If you're validating empty input, custom validators don't fire if you set the ControlToValidate property AND don't set the ValidateEmptyText property to true, otherwise the framework expects you to use a RequiredFieldValidator.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.validateemptytext.aspx
If you set the ControlToValidate property the CustomValidator won't fire if the user doesn't enter/select anything. But if you omit it it will fire always when the form is submitted.
So remove it.
<asp:CustomValidator ID="ValidateEndTime"
OnServerValidate="ValidateEndTimeFun"
runat="server" ErrorMessage="*required">
</asp:CustomValidator>
Since you're validating multiple controls i would do it that way, otherwise you could also set the ValidateEmptyText property to true as gfyans has mentioned.
I think that the ValidationGroup element is missing.
You should the same value for ValidationGroup it to the validator and to the button, too (or checking it programmatically using Validate method of the Page) that has to check the value.
It's been a long time since I used it without an updatepanel as this is also an answer I found by Sarawut Positwinyu:
Custom Validator, when placing in formview will not show its error message after
server-side validation (though it has been validated and result is invalid) the
mean to fix this in to wrap it by a Update Panel.
I also remember always putting in the validationgroup="name of the group" for all controls which are validatedand putting validateemptytext to true for the custom validator.
answer reference
why don't you use different validator for different controls? and also to work custom validator in server just discard the ControlToValidate property from the tag. and also check the condition you have used in code behind.
Here is a part of my ASP.NET page.
<asp:DropDownList ID="DropDownList1" runat="server"
OnChange="return ListChange(this.value)"
onselectedindexchanged="DropDownList1_SelectedIndexChanged1"
AutoPostBack="True" >
<asp:ListItem Selected="True">Today</asp:ListItem>
<asp:ListItem>Yesterday</asp:ListItem>
<asp:ListItem Value="1">Specific Day</asp:ListItem>
<asp:ListItem>All Time</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
Here is the Javascript.
function ListChange(txtVal) {
if (txtVal != 1 ) {
document.getElementById("txtDate").setAttribute("style", "visibility:hidden;");
return true;
}
else {
document.getElementById("txtDate").setAttribute("style", "visibility:visible;");
return false;
}
}
Here the objective is to show certain data according to the option selected by the user. In the Specific Day option, a textbox is shown to the user to insert date through javascript. But the onselectedindexchanged event is also raised which calls to server. I want to stop the event when "specific day" option is selected, but run when other options selected.
The code on OnChange="return ListChange(this.value)" is not stopping the event as used to when using a form with button.
It is one of the options that you can use.
Remove the selected index change event from markup.
on change event , check whether your validation has ran correctly.
if they have run make ajax request and do your stuff.
you do not need to call two separate functions simultaneously. Here is some jquery code that will do the trick in just a few lines.
$(document).ready(function(){
$('#DropDownList1').change(fnction(){
if($(this).text() != 'Specific Day') {
document.getElementById("txtDate").setAttribute("style", "visibility:hidden;");
return true;
} else {
document.getElementById("txtDate").setAttribute("style", "visibility:visible;");
return false;
}
});
});
By default ASP.Net will post back if you give AutoPostBack =true.
It is not considering return values.
Below is the code rendered at execution time. it uses settimeout and executed _doPostBack for submitting Form
onchange="return ListChange(this);setTimeout('__doPostBack(\'ctl00$MainContent$DropDownList1\',\'\')', 0)"
We need to think about stopping a form submit by setting a flag like Page_IsValid=false;
I would suggest that you do the show & hide using the .net code.
For example in VB.net
Put the following code in the DropDownList1_SelectedIndexChanged1 sub.
If DropDownList1.SelectedValue = "1" Then
txtDate.Visible = True
Else
txtDate.Visible = False
End If
Rather than have 3 different on click/change events.
Then remove the JS and the on change and on client click events, just leave it with onselectedindexchanged="DropDownList1_SelectedIndexChanged1"
UPDATE:
If you want to avoid postback for some events in your code do :
If isPostBack = True
//Don't fill form stuff
Else
//Fill form stuff
End If
First try to check what value is coming in your javascript function.
If its not showing the selceted value use the following code
var index = document.getElementById(selectItem).selectedIndex;
alert("value =" + document.getElementById(selectItem).value);
alert("text =" + document.getElementById(selectItem).options[index].text);
or using jQuery
$("#yourdropdownid option:selected").text();
In C#, is it possible to get a bool value, determining if the cursor is currently inside a certain textbox?
What I want to achieve:
I have a masterpage, with two buttons in it; a search-button and a login-button. Depending on what textbox is active or has focus, or of none have focus, I want to set the UseSubmitBehavior-attribute.
What I want to happen is something like this (I know this code doesn't work):
if (textboxUsername.hasfocus == true || textboxPassword.hasfocus == true)
{
buttonLogin.UseSubmitBehavior = true;
buttonSearch.UseSubmitBehavior = false;
}
else
{
buttonLogin.UseSubmitBehavior = false;
buttonSearch.UseSubmitBehavior = true;
}
The goal is to make the page react the way the user expect it to, e.g. actually searching when hitting enter, and not trying to login, when you are typing in the search-field.
What you are trying to do won't work like that.
What you can do however is enclosing the login fields in a panel and the search field in a panel, and then you add a DefaultButton to both of them.
<asp:Panel runat="server" ID="SearchPanel" DefaultButton="Search">
<asp:TextBox runat="server" ID="SearchInput" />
<asp:Button runat="server" ID="Search" />
</asp:Panel>
If you press enter in this textbox the search button will do the postback.
Note: this does not work with LinkButtons or ImageButtons, if you use these you can add a workaround: add a normal Button and set it's style to display:none; and let the LinkButton and Button trigger the same event.