I have a form with a custom validator for the date:
<asp:CustomValidator runat="server" ID="cusCustom"
ControlToValidate="fdate"
Display="None"
OnServerValidate="customdate"
ErrorMessage="You need to book 24 hours earlier" />
<ajaxToolkit:ValidatorCalloutExtender
ID="ValidatorCalloutExtender4"
TargetControlId="cusCustom" runat="server">
</ajaxToolkit:ValidatorCalloutExtender>
And the function behind:
protected void customdate(object sender, ServerValidateEventArgs e)
{
string dateString = String.Format("{0} {1}:{2}:00", fdate.Text, TimeSelector1.Hour, TimeSelector1.Minute);
DateTime selectedDateTime = new DateTime();
if (DateTime.TryParse(dateString, out selectedDateTime))
{
if (selectedDateTime > DateTime.Now.AddHours(24))
{
e.IsValid = true;
} else {
e.IsValid = false;
}
}
}
The problem is that it works fine, it detects what it needs to detect and it triggers the warning, but... it triggers it too late! If I enter a wrong date in the form, I am able to submit it, and I will find the warning about this bad validation next time I open the modalpopup with the form to enter a new booking.
All the other validators I have in the same form work fine. This is the button that launches the form:
<asp:Button ID="btnNew" runat="server" Text="New" CausesValidation="false" />
It has the CausesValidation set to false, and that works very well for the normal validators. Is only the custom one that runs too late...
Any suggestions?
You should probably have your popup firing an event to check whether the input is valid after you close it. I'll provide you with some pseudo-code.
<popupModalBox OnClose="PopupModal_OnClose" />
Triggering a method on the server
void PopupModal_OnClose(object sender, EventArgs e)
{
if (Page.IsValid)
{
// Do something
}
else
{
// Do something else
}
}
Related
I only have one textbox on the page. For this textbox I have a textbox text change event in the code behind. Since this is the only element on the page, it's only firing after user enters input and user hits space button. Is there a hack I could use to make textbook tex changed event happen once it looses focus instead of user hitting space button?
<asp:Textbox Id="txtInputID" runat="server" TextChanged="ReadWriteTB_TextChanged" />
private void ReadWriteTB_TextChanged(object sender, RoutedEventArgs e)
{
//do stuff here
}
Update - I use jquery auto complete for this textbox. Not sure if that is causing user to hit space button.
Try this:
private void ReadWriteTB_TextChanged(object sender, RoutedEventArgs e)
{
txtInputID.Attributes.Add("onfocus", "javascript:this.value=this.value;")
txtInputID.Focus()
}
<script type="text/javascript">
var MIN_TEXTLENGTH = 3;
function forcePostback(ctrl) {
if (ctrl != null && ctrl.value && ctrl.value.length >= MIN_TEXTLENGTH) {
__doPostBack(ctrl.id, '');
}
}
</script>
...
<asp:TextBox ID="txtInputID" OnKeyUp="forcePostback(this);" AutoPostBack="true"
OnTextChanged="ReadWriteTB_TextChanged" runat="server"/>
i understand that we able to achieve this by using "onClientClick", but i want to check the validation first BEFORE the confirmation box.
javascript
function showConfirm() {
var result = window.confirm('Are you sure?');
if (result == true)
alert("ok");
}
html
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
C#
protected void Button1_Click(object sender, EventArgs e)
{
if(checkValidation() == true)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scr", "javascript:showConfirm();", true);
//if(result == true) //how to get the result value?
//{
////run some code
//insert data into sql
//}
}
}
is there anyway i can get the confirmation result at code behind? without the if-else-statement, the data will insert into sql before user choose their decision.
i create a button with display:none
.hideButton{
display:none;
}
create code behind
protected void btnConfirm_Click(object sender, EventArgs e)
{
Response.Redirect("page2.aspx");
}
trigger the btnConfirm click if user click Yes on confirmation box
$('#ContentPlaceHolder1_btnConfirm').trigger('click');
If you are doing a custom validation in Web forms that you much enable EnableClientScript="true" and write the JS validate function name in ClientValidationFunction="JSValidateFunctionName" like this you would be able to validate on client side before even going to server side.
How can I invalidate the page in textchanged event.
I have a simple form with textboxes and a button to submit
I would like to disable the button or stop the submission if the text entered is not valid.
the validity is to be checked in the textchanged event since I have some db operation to check the validity of the content.
If I can somehow invalidate the page in the textchanged event then it might be easier
pls give me some easy way to implement this
thanks
Shomaail
I was able to resolve my own problem perfectly. I used the customvalidator OnServerValidate Event
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.onservervalidate(v=vs.110).aspx
Now in my TextChanged event I show up a warning if the data entered is not correct and in the button_click event of my submit button I call Page.Validate() that subsequently calls OnServerValidate event handler of each custom validator associated with a text box.
protected void btnIssueItem_Click(object sender, EventArgs e)
{
Page.Validate();
if (!Page.IsValid)
return;
....
}
protected void tbRoomID_CustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
BAL bal = new BAL();
args.IsValid = bal.GetRoomByRoomID(Int32.Parse(args.Value)).Count == 0 ? false : true;
}
You can set Button Enabled Property to true of false, ie:
<asp:TextBox runat="server" ID="txtData" OnTextChanged="txtData_TextChanged"
AutoPostBack="true"></asp:TextBox>
<asp:Button runat="server" ID="btnSave" OnClik="btnSave_Click"></asp:Button>
On Code Behid:
protected void txtData_TextChanged(object sender, EventArgs e)
{
if(txtData.Text == "something")
{
btnSave.Enabled = True;
}
else
btnSave.Enabled = False;
}
I have the following in my .aspx file:
<asp:CustomValidator
ID="JobIDCustomFieldValidator"
runat="server"
ControlToValidate="JobID"
OnServerValidate="jobIDCustom_ServerValidate"
EnableClientScript="false"
SetFocusOnError="true"
Display="Dynamic"
ErrorMessage="! - Not Found"
CssClass="validationError">
</asp:CustomValidator>
<br />
<asp:TextBox ID="JobID" runat="server"></asp:TextBox>
<asp:Button runat="server" ID="ProcessButton" Text="Process" onclick="ProcessButton_Click" />
I have the following in my code behind file:
protected void ProcessButton_Click(object sender, EventArgs e)
{
Response.Write("I am in here");
}
protected void jobIDCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
// Impersonate a user for shared folder access.
using (UserImpersonation user = new UserImpersonation(properties.ShareUser, properties.Domain, properties.SharePassword))
{
e.IsValid = false;
// Check the user credentials.
if (user.ImpersonateValidUser())
{
e.IsValid = File.Exists(#"\\\\" + properties.RemoteServer + "\\" + properties.Share + "\\" + JobID.Text + ".dat");
}
}
}
I want the custom validator to be checked first and if it is false stop and do not run any of the code in the ProcessButton_Click() method. Is this possible? If not is there an alternative way I could set this up?
As far as I know I can't use client side validation with javascript to do the impersonating and file access.
Any help would be greatly appreciated.
To summarize check to see if the page is valid in the button click handler.
protected void ProcessButton_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//do button stuff
}
}
"Validation controls test user input, set an error state, and produce error messages. They do not change the flow of page processing—for example, they do not bypass your code if they detect a user input error. Instead, you test the state of the controls in your code before performing application-specific logic. If you detect an error, you prevent your own code from running; the page continues to process and is returned to the user with error messages."
From MSDN
http://msdn.microsoft.com/en-us/library/dh9ad08f(v=vs.90).aspx
What way is standard/ recommended to do the following:
When a user raises the Page_Command "Save" or "Send," I want to run a method. If the method returns false, I want to send the user back to the page and display a message.
All of the data they entered in the form should still be there. The message would have a button that reads, "Send Anyway/ Regardless." If they click it, it will send.
I know I could do this via a webservice and jQuery, but I am asking how I would do this via WebForms.
Here is my basic code:
protected void Page_Command(Object sender, CommandEventArgs e)
{
if ( e.CommandName == "Save" || e.CommandName == "Send" )
{
// run method
}
}
There are several ways you could do this.
One option might be to a button with the text "Save", and another with the text "Send anyway". Make the second button invisible to begin with, and the first visible.
When the first button is clicked, it should run the validation-logic. If validation succeeds, submit - otherwise, hide the first button, and set the other one to visible.
When / if the second button is clicked, the submit is performed without validation.
Update:
With some minor modifications, you should be able to do something like this:
Markup:
<asp:Button runat="server"
ID="myFirstButton"
OnClick="SubmitWithValidation" />
<asp:Button runat="server"
ID="mySecondButton"
Visible="False"
OnClick="SubmitData" />
Code:
protected void SubmitWithValidation(object sender, EventArgs e)
{
if (ValidateMyData())
{
SubmitData(sender, e);
}
else
{
mySecondButton.Visible = true;
myFirstButton.Visible = false;
}
}
private bool ValidateMyData()
{
// Validate stuff
return isValid;
}
private void SubmitData(object sender, EventArgs eventArgs)
{
// Logic to submit your data here
}