How to prevent PostBack on the client side? - asp.net

I have some validation JS code on client, that must be executed befor PostBack.
If this validation code return 'false', postback is needless.
How it can be disabled?

Remember that the real validation should always happen on the server. Anything you do client-side is merely an optimization to save a few http round trips.
The easiest way to keep your client side and server-side validation in sync with ASP.Net is to use the validation controls. The validation controls will do both client side and server side validation, in such a way that if validation fails on the client it never posts to the server.
If you want to do something that's not covered by the standard validation controls, you should either use a CustomValidator or inherit your own control from BaseValidator.

Set the OnClientClick='YourJSValidationFunction' on your ASP button.
Then have the YourJSValidationFunction return true or false.
False will prevent postback
Example:
http://vijaymodi.wordpress.com/2007/06/08/button-onclick-and-onclientclick-2/

If the postback is being triggered by a button then you can do something like this:
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return IsValid();" />
If the IsValid function returns false then the postback will be prevented.
If you want to catch all postbacks regardless of which control triggers it then you can use <form id="form1" runat="server" onsubmit="return IsValid();">

What do you use: some validator or some button with onclick event?
If you have
<input type="button" id="btnID" runat="server" onclick="CheckValid();"/>
function CheckValid()
{
if(!IsValid) return false;//then no post back occer
}

Depending on the validation you're attempting, you may also be able to use the CustomValidator control. This would also allow you to easily implement your validation logic on the server side.

Related

Prevent page refresh in ASP.NET

I have the following code in my aspx file:
<button type="button" id="btnAskQuestion" runat="server" onserverclick="btnAskQuestion_Click">Ask Question</button>
I've tried every combination of onclick="return false;" and onclick="preventDefault()" I can think of, including putting them in the javascript function that gets called. Everything I try has one of two results: either I get a postback, or the server side code (btnAskQuestion_Click) never executes.
Any idea what I might be doing wrong?
You cannot execute server-side code this way, using onserverclick causes postback.
If you wish to prevent full page refresh and still execute server-side code, you have to call a client-side JS function via onclick and execute an AJAX call from there.
Another alternative is to use your button as a trigger for UpdatePanel - this way only partial postback will be performed.
Try using the property UseSubmitBehavior="false" in the button markup.
or you can use a "trick" :
Markup
<button onclick="myFunction()">Click Me!</button>
<div style="display:none">
<asp:Button runat="server" id="btnButton" .../>
</div>
js
function myFunction()
{
if (true statement)
$("[id$=btnButton]").click();
else
alert("false");
}
What this does is that you handle stuff with normal markup and do the logic using js. And you can trigger a click of the button that do something in the server.
There're OnClick, that fires on server and OnClientClick that fires on client browser. You should do this:
<asp:Button ID="btnAskQuestion" runat="server"
OnClick="btnAskQuestion_Click"
OnClientClick="return myfunction();">Ask Question</asp:button>
If myFunction returns true, then you will have a postback to the server.
My answer is appropriate only for ASP:Button, not the button control you are working with. Given the choice, I'd switch to ASP:Button.
You're looking for OnClientClick. If you put your JavaScript code there, it will kill the PostBack before it can hit the server.
On the other hand, if you're looking to execute server code without a PostBack, that's impossible. The PostBack is what triggers the server to act.

Why does CustomValidator fire on textbox's onblur

I am building a CustomValidator to handle my own application's logic on time fields ("09:00", "15:35", ...) but I am stumbling on a behaviour that I haven't found any explanation for online.
My focus right now is the validation logic that gets executed client-side.
The problem is, as said in the title, that, if and only if I set the ControlToValidate property in the Validator with the ID of the textbox I am validating, the validation gets fired as soon as focus leaves the textbox; it even fires before the onblur event, which is absolutely detrimental for me, since I am using the onblur event to standardize the time formats (eg "9:00" -> "09:00", "11.45" -> "11:45") and thus, the validation logic potentially receives an incorrect value. If, on the other hand, the ControlToValidate property remains blank, the ClientValidationFunction is fired only on a submit/postback.
The only related answer I've found is this https://stackoverflow.com/a/8649697/450684, but still, to me it makes no sense at all. Why should the presence of a ControlToValidate indicate that I want client-side validation to execute before onblur? I don't want it! Is there any way to supress this behaviour?
Here is an example page:
<asp:TextBox runat="server" AutoPostBack="false" ID="txtBox1" onblur="FormatText(this);" />
<asp:CustomValidator runat="server" ID="CV1" ControlToValidate="txtBox1" ClientValidationFunction="Test1" />
<asp:CustomValidator runat="server" ID="CV2" ClientValidationFunction="Test2" />
<asp:Button ID="btn1" Text="postback" runat="server" OnClick="btn1_Click" />
<asp:Label ID="lbl1" runat="server" />
<script type="text/javascript">
function FormatText(txtBox1)
{
alert('FormatText');
}
function Test1(val, args)
{
alert('Test1');
}
function Test2(val, args)
{
alert('Test2');
}</script>
What I want is both Test1 and Test2 to execute only on btn1's click; instead on txtBox1's onblur event I get Test1 and FormatText executing in this order
ASP.NET's client validation was really fun for me to write and study, don't let this ruin everything :-)
Thx
PS: .NET framework's version is 4.0. Plus, the server-side language is C#, if it matters
I think what is going on is this:
The standard behavior for ASP.NET client-side validation is to validate when the field is exited. That's an observation, not a reference to a published standard (although there may be one.) The out-of-the-box validators all behave this way. All of them require specifying a particular field to validate.
The custom validator allows you to validate a single control (by specifying it with ControlToValidate), or lets you validate a combination of controls, in which case you set ControlToValidate to an empty string. Unless things have changed, you do have to specify it; if you omit the attribute, no validation will occur.
So ... if you specify a control to validate, the custom validator behaves like every other validator and reacts to the user exiting the field. If you don't specify a control to validate, it doesn't know what controls you're interested in, and doesn't do that.
You may be able to work around this by writing a truly custom validator: inherit from BaseValidator. That can actually be a lot of fun.
How to manage events of validation for your control.
You can remove ControlToValidate property from your validator and bind validation for your textbox on textbox event as you wish. You can add some function logic before or after validation also. On button click event validation stay the same without change.
function BindValidation(){$('#txtBox1').on('blur keyup change',function(){ValidatorValidate($('#CV1').get(0));});}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(BindValidation);
//validation function example for CV1 validator
function Test1(val, args)
{
args.IsValid=$('#txtBox1').val().length>0&&$('#txtBox1').val().match(/^\s+$/g)==null;
}

how to check a particular asp.net validation control is valid?

In a web form there are different asp.net validation controls. Is it possible to check a particular validation control is valid ? For example on leaving focus of textbox, first I will check requiredFieldValidatorUserName is valid ? If it is valid then I will check on server using ajax that this user name is not booked already.
Edit:
Explaination: I want to check validity (that input was valid) of a validation control on client side.
Please guide.
All validator controls implement IValidator which contains the IsValid property.
myValidatorControl.IsValid
The best way would be to use a CustomValidator with client side code, as this will display all the error messages, block form submission and also ensure that the validation is repeated at the server side - remember, just because you have client-side validation available, doesn't mean the user's seen it: Always validate your input at the server as well.
Your CustomValidator would then be coded to call the Ajax methods, and would show the error messages correctly to the client:
<asp:Label ID="UserNameLabel" AssociatedControlID="UserName" runat="server">
UserName *:</asp:Label>
<asp:TextBox ID="UserName" runat="server" />
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server"
ControlToValidate="UserName" EnableClientScript="true"
ErrorMessage="You must supply a username!" />
<asp:CustomValidator ID="UserNameCustom" runat="server"
ControlToValidate="UserName"
ClientValidationFunction="CheckExisting"
OnServerValidate="UserNameCustomValidate"
ErrorMessage="Username already taken" />
And your ClientValidationFunction should look something like:
<script type="text/javascript">
function CheckExisting(source, arguments) {
// Pass the arguments.Value to your AJAX call:
if (ajaxCallUserNameTaken(arguments.Value)) {
arguments.IsValid = false;
}
}
</script>
(Obviously, you'll need to write the ajaxCallUserNameTaken method to call your page method/web service/etc.)
Doing it this way will ensure that the validation methods happen as expected; this will get called whenever the user tabs out of the textbox leaving a value (it won't get called if the textbox is empty), and will ensure that the user can't submit the page until they supply a unique value. You'll also want to create the method referenced in OnServerValidate to ensure that the value's good once it hits the server too - this should call the same code that the AJAX endpoint uses to reduce duplication of code, etc.
I was originally going to suggest that you could use the Page_Validators object on the client-side to do some checking in the onBlur event, but I don't really think this is suitable here as it results in more pain:
It assumes that although there might be more than one validator on the page, there's only the RequiredFieldValidator on the control we're checking
The RequiredFieldValidator isn't fired during OnBlur if a user moves out of a control without setting a value - only if they set and clear the value, so even if isvalid is true, you need to check for an empty string!
You could do this by setting the ValidationGroup for the Validator control that you want to treat as separate from the others. Make sure it matches the ValidationGroup of the control it's validating (your username field).
I have just faced the same issue and I Set CausesValidation="true" to the textbox control and it worked. Just give it a try :)
I have been messing around with this around for a bit and found a rather easy (not so efficient) solution to handle this using jQuery.
Use this function to check the validity of your control:
function validateControl() {
return $('#YOUR_VALIDATOR_ID').css("visibility") == "visible"
if you're using Display="Dynamic" on your validator then the function is like so:
function validateControl() {
return return $('#YOUR_VALIDATOR_ID').css("display") == "inline"
Be sure to check the true ID of your validator if you're using a Masterpage, as it will be different than the one in your IDE. Do so by viewing the page source in your browser.
The best solution will be of course to validate your form in some other way, using JavaScript or a CustomValidator that lets you write your own code.

From client, force whole page validation

I have an ASP button for which I have set the OnClientClick property to display a javascript confirm message. However, I only want this message to be displayed AFTER all of the client side validations have passed.
How can I do this? Essentially, I believe that I need to force Page level validation from the client and then, only if it passes, display the confirmation box.
If you're using the ASP.NET validation controls add an OnClientClick like this to your submit button...
<asp:Button ID="blah" OnClientClick="if(Page_ClientValidate())return confirm('your message')" OnClick="your submit method" Text="submit" runat="server" />
...Page_ClientValidate() will return true if the page is validated then you need to return the results of your "confirm" in order for the form to be submitted.
There's something along these lines available here: http://www.codeproject.com/KB/aspnet/JavascriptValidation.aspx

ASP.NET CheckBox disabling postback with javascript

I'm trying to wire up a CheckBox to handle an event when check/unchecked. If the user has JavaScript enabled, use that, otherwise use a postback.
Here is my code:
<asp:CheckBox ID="ApplicationInProcessCheckBox" runat="server"
Text="Application In Process" AutoPostBack="true"
oncheckedchanged="ApplicationInProcessCheckBox_CheckedChanged"
onclick="return false;" />
The return false in the javascript onclick event is disabling the postback. However, it also won't let the box check or uncheck. (I have more code to add to the javascript event... I just want to get the concept working first).
What am I doing wrong?
I think we can't post back on clicking checkbox without Javascript enabled.

Resources