I need to run some script by onclick() of some , checkbox particularly, to decide should i invoke WebForm_doPostBack() or not.
If I will submit form in myScript() myself, it will not cause validation of another asp.net validators, so I really need a native WebForm_doPostBack() call.
Should I handle a submit form event or are there any more "asp.net" ways to do it?
CustomValidators don't work with checkboxes:).
Just to ensure your assumptions that custom validators do not work with checkboxes is not the ONLY reason for wanting to handle the checkbox click seperately, here is some code that will validate checkboxes using ASP.NET custom validators.
Custom Validators have a ClientValidationFunction property that is called automatically when the __doPostback is called or the form is submitted.
//The Script
function validateCheckBox(source, arguments)
{
if(!source.checked) arguments.IsValid = false;//set IsValid property to false
}
//The Validator
<asp:CustomValidator ID="validateCheckbox" runat="server" ControlToValidate="CheckBox1" ErrorMessage="You REALLY need to check this!" Display="Static" ClientValidationFunction="validateCheckBox"/>
Don't you try simply putting your own validation at submit button like that :
btnSubmit.Attributes["onclick"] += "return myValidation();";
<script>
function myValidation()
{
// if you do not want to postback just return false...
return true;
}
</script>
EDIT : You can use Page_ValidationActive to programmatically enable / disable the client side validation of your page.
Page_ValidationActive A Boolean
value that indicates whether
validation should take place. Set this
variable to false to turn off
client-side validation
programmatically.
Related
I have a custom user control which contains a textbox and some other logic / controls, including a custom validator. When dropping my custom control on an aspx page, i want to be able to attach a method to the customer validator within the control, by providing a value for the OnServerValidate property in the html.
How can this be done? I want to be able to pass the validation method name as a property in the user control's html, rather than having to attach to the custom validator's event through the code behind.
You can wrap custom validator's ServerValidate event into your own, and then use it in the markup for the handler assignment. In you control all that is needed is a proper declaration of the event:
public event ServerValidateEventHandler ServerValidate
{
add { this.CustomValidator1.ServerValidate += value; }
remove { this.CustomValidator1.ServerValidate -= value; }
}
Now in the markup it is possible to sign up for this event, effectively signing up for the custom validator's event at the same time:
<yourTagPrefix:YourControlName
OnServerValidate="YourControlName_ServerValidate"
runat="server"
... />
We have a form with a number of required fields. When I am on a required field and I hit the enter key the form does not submit. However, if I'm on a field that is not required, hitting the enter key does submit the form. This is problematic because submitting the form is what fires the validation to display the validation summary at the top. If I'm on a required field it doesn't fire this validation. It does seem to fire it's own validation and display my error text (which is just an asterisk) but people are not seeing this.
Does anyone know why a non-required field enter key would submit the form but a required field enter key wouldn't?
From what you've described, it sounds like you're using server-side validation. Try setting EnableClientScript to false on the validator, which will disable client-side validation.
If this is not enough, you can override the validation when the submit button is clicked like this:
<script type="text/javascript">
validateForm = function(){
var isValid = Page_ClientValidate("");
if (isValid){
//some custom logic if needed
}
return true; //do the postback even if validation fails?
//otherwise return isValid
}
</script>
<asp:Button ID="Button1" runat="server" OnClientClick="return validateForm();" ... />
I have scenario, Page contains Check in date and Check out date for input. I used user control for datepicker, so both dates are called same user control.
Like,
Check In Date: <uc:datepicker ID="CheckInDate" runat="server" />
Check Out Date: <uc:datepicker ID="CheckOutDate" runat="server" />
Now I do validation for both dates which should not be blank like.
public class CustomiseDatePickerValidator : BaseValidator
{
protected override bool EvaluateIsValid()
{
Control c = this.FindControl(this.ControlToValidate);
DatePicker datepickerSelected = c as DatePicker;
ICustomiseRadDatePicker additionUserControl = (ICustomiseRadDatePicker)c.Parent;
if (string.IsNullOrEmpty(datepickerSelected.DateInput.Text))
{
return false;
}
return true;
}
}
This is working fine but I want also compare both datepicker value So Check in date Should be less than Check out date
It would probably be easier to use a CustomValidator for this. With the CustomValidator, you can specify your own client-side validation logic.
See this question for more details:
ASP.NET Custom Validator Client side & Server Side validation not firing
I may be wrong, but i think you need to use a CompareValidator for this. Correct me if i am missing something
A better solution to a CustomValidator is to apply the ValidationPropertyAttribute to the user control class. That way you can use normal ASP.NET validators against the user control as you would any other control.
I have a button control. Once the user clicks on it, the click event should fire and then the button should get disabled. How can I do this? I have the option to use JQuery or JavaScript or both.
Here is my button declaration:
<asp:Button
ID="Button1"
runat="server"
Text="Click Me"
onclick="Button1_Click"
/>
On the button click code behind, I have added a Response.Write(). That should get executed and then the button should be disabled
For whatever reason, the HTML spec dictates that disabled elements should not be included in POST requests. So, if you use JavaScript to disable the HTML element in the client-side onclick event, the input element will be disabled when the browser assembles the POST request, the server won't be properly notified which element raised the postback, and it won't fire server-side click event handlers.
When you set the UseSubmitBehavior property to false, ASP.NET renders an input element of type button instead of the regular input of type submit that the ASP.NET Button control normally generates. This is important because clicking a button element does not trigger the browser's form submit event.
Instead of relying on a browser form submission, ASP.NET will render a client-side call to __doPostBack() within that button element's onclick handler. __doPostBack will raise the postback explicitly, regardless of what POST data comes through in the request.
With the postback being raised independent of the browser submit event, you're freed of the previously mentioned HTML quirk. Then, you can set an OnClientClick of "this.disabled = true;", which will render as "this.disabled = true; __doPostBack('Button1', '');", and things will work as intended.
add an OnClientClick="this.disabled = true;" to your button.
If you are using Asp.net Ajax you might want to look at using PostBack Ritalin.
Have you tried this?
Add an OnClientClick="MyFunction();" to your .NET button.
Then in the .aspx page script tags you add the following JS function:
<script type="text/javascript">
function MyFunction()
{
window.setTimeout(function ()
{
// get the button/control to disable using your favourite clientside ...
// ... control grabbing code snippet ...
// ... eg. JQUERY $('Button1'), getElementById, etc.)
document.getElementsByName('Button1').Button1.disabled = true;
// I've used "getElementsByName" because .NET will render a button with
// ... a "name" attribute, and not an "id" attribute, by default
}, 1);
}
</script>
This gives the browser a chance to post back, followed by a quick button disable.
You need to be careful that the postback occurs before you disable the button through client script. This is a common gotcha with ajax and input boxes. Disabling an input box prevents the data from being sent from the browser, even if you can see text within it while it is disabled. The answer is that you need to use jquery for this to ensure the server-side code runs first before it is disabled.
-Oisin
// to disable
this.setAttribute('disabled', true);
// to enable
this.removeAttribute('disabled');
this is a cross browser solution
There is really cool event for body tag "<"body onBeforeunload="buttonId.disabled = true;" ">"
This event triggers right before form submits, in other words your data will be submitted correctly.
When using the "this.disabled = true" method make sure you check if the page is valid before disabling the control if you have validators on the page. If validation fails you won't be able to re-enable the control without reloading the page.
if (Page_IsValid) this.disabled = true;
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function BeginRequestHandler(sender, args) {
document.getElementById('<%= lblMessage.ClientID %>').innerText = "Processing...";
document.getElementById('<%= btnSubmit.ClientID %>').innerText = "Processing";
args.get_postBackElement().disabled = true;
}
</script>
Add Script Tag in source page . change Id of button in code . You can disable the button till the process completes execution .
you can disable it server side
Button1.Enabled = false;
Related Article
On a similar topic to the above article, but of a more specific note. How exactly do you handle items that are in the viewstate (so they are included on submit), but can also be changed via AJAX. For instance, say we had a dropdown list that was populated through an AJAX web service call (not an update panel). How can I get the page to validate once the dropdownlist's items have been changed?
You're not validating the dropdown list are you? You're validating the value a user selected. It's pretty much the same advice as the other post, since javascript or other tools can alter the html or create their own POST's, you must always validate on the server side. Assume all client requests can be tampered with, and assume that no client-side validation has occurred.
If you're using the web forms model ....
If you just want to check a value was selected in the dropdown myAjaxDropDown, use the
<asp:RequiredFieldValidator id="dropdownRequiredFieldValidator"
ControlToValidate="myAjaxDropDown"
Display="Static"
InitialValue="" runat=server>
*
</asp:RequiredFieldValidator>
You could also want to look at the asp:CustomValidator - for server side validation:
<asp:CustomValidator ID="myCustomValidator" runat="server"
onservervalidate="myCustomValidator_ServerValidate"
ErrorMessage="Bad Value" />
Both plug into the validation framework of asp.net. e.g. when you click a button called SumbitButton
protected void myCustomValidator_ServerValidate(object source, ServerValidateEventArgs e)
{
// determine validity for this custom validator
e.IsValid = DropdownValueInRange(myAjaxDropDown.SelectedItem.Value);
}
protected void SubmitButton_Click( object source, EventArgs e )
{
Validate();
if( !IsValid )
return;
// validators pass. Continue processing.
}
Some links for further reading:
ASP.Net 2.0 Quickstart - Validating Form Input Controls
ASP.NET Validation Controls – Important Points, Tips and Tricks
You can call the Page_Validate() function from your javascript code, it will trigger the asp.net validators on the page, it is basically similar to Page.Validate() in server code
why not validating onChange even in the dropdownlist?
just add the script manager and add that property to the onchange in the Page_Load event
' Creating the javascript function to validate
Dim js As String
js = "function validateDDL1(ddl) { alert(ddl.value); }"
' Adding onChange javascript method
DropDownList1.Attributes.Add("onchange", "validateDDL1(this);")
' Registering the javascript
ScriptManager.RegisterClientScriptBlock(Me, GetType(String), "validateDDL1(ddl)", js, True)