javascript error handling - asp.net

I have a javascript function for checking errors which I am calling on OnClicentClick event of a button. Once it catch a error I want to stop execution of the click event. But in my case it always it always executes the onclick event.
Following is my function:
function DisplayError() {
if (document.getElementById('<%=txtPassword.ClientID %>').value.length < 6 || document.getElementById('<%=txtPassword.ClientID %>').value.length > 12) {
document.getElementById('<%=lblError.ClientID %>').innerText = "Password length must be between 6 to 12 characters";
return false;
}
var str = <%=PhoneNumber()%>;
if(str.length <10)
{
alert('<%=phoneNum%>'.length);
document.getElementById('<%=lblError.ClientID %>').innerText = "Phone Number not in correct format";
return false;
}
}
button html code:
<asp:Button runat="server" Text="Submit" ID="btnSubmit" ValidationGroup="submit" onclick="btnSubmit_Click" OnClientClick="DisplayError()"/>
It should not execute the button click event once it satisfies any of the IF condition in the javascript function.

Use OnClientClick="if (!DisplayError()) return false;"
That way, if no error occurred, it will still postback, but only when an error occurs, it will return false, and cancel the postback.

Use OnClientClick="return DisplayError();"

Related

how to check if validationgroup passed?

Currently working with UserControls.
Have this button :
<dx:ASPxButton ID="btnSave" runat="server" Text="Save" CssClass="btn btn-active" ValidationGroup="MyValidationGroup" OnClick="BtnSaveClick">
I inherited this code from my team mates.
Recently i discovered that if button is clicked multiple times, it duplicates the record.
I tried to add
btnSave.ClientEnabled = false;
and
btnSave.Enabled = false;
into the code behind, but it's not preventing from duplicating the records.
How to check if validation group passed (successfully) into jquery or javascript, than disable the button on the front end ?
Any idea ?
well simply use
<asp:Button ID="btnSave" runat="server" class="btn btn-active" OnClick="btnSave_Click" ValidationGroup="validation" Text="Save" OnClientClick="if (!Page_ClientValidate()){ return false; } this.disabled = true; this.value = 'Saving...';"
UseSubmitBehavior="false" />
This code snippet will disable your button and doesn't allow use to click multiple times until click event executing its code
Hope this will help :)
If you do not want duplicates, why not check them at the database level? Disabling a button will help with double clicking. But you will still get the same result if a user presses F5 or reloads the page as new and then presses the button again.
For MS SQL you could do something like this:
IF NOT EXISTS (SELECT column FROM table WHERE (column = #myVar))
INSERT INTO table (column) VALUES (#myVar)
Or you could also place a constraint on the column
ALTER TABLE table ADD CONSTRAINT UQ_column UNIQUE (column)
you can do this $(document).ready(function(){
$('#ctl00_MainContent_btnSave')
.attr("onclick", null)
.removeAttr("onclick")
.click(function() {
// To validate you form using Validation group.
if (typeof (Page_ClientValidate) == 'function') {
Page_ClientValidate("ValidationGroup");
if (Page_IsValid == true) {
alert('the form is valid');
}
} else {
if ($(this).valid()) {
alert('the form is valid');
}
}
//Disable button before page posting back
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions($(this).attr("name"), "", true, "", "", false, false));
});
});
I figured it out. When i used code #Shayan Hafeez provided, compiler thrown an exception.
The server tag is not well formed.
Than, i removed OnClientClick from the button and insert this code into code-behind :
btnSave.ClientSideEvents.Click = "if (!Page_ClientValidate()){ return false; } this.disabled = true; this.value = 'Saving...';";
It works fine now.

How to show form data with confirm and cancel button before saving data in data base?

How is it possible ? I have used ASP.Net text box and label controls.
Many Thanks
On save Button try to give OnClientClick
aspx Save button
<asp:Button ID="btnsave" Text="Save" runat="server" OnClientClick="javascript: return test()" OnClick="serversave_click"></asp:Button>
Javascript:
function test() {
var empText = document.getElementById("<%=txtname.ClientID%>").value;
if (confirm('Are You Certain to save this Name:'+ empText + '?')) {
return true;
}
else {
return false;
}
}

Prevent double clicking asp.net button

I realise this question has been asked but none of the answers worked for my project.
I have a button that when clicked calls an API, so there is a 1 second delay.
I have tried several things nothing works.
btnSave.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btnSave, null) + ";");
Even that does nothing.
Prevent Double Click .Please add below code in your aspx page.
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function BeginRequestHandler(sender, args) { var oControl = args.get_postBackElement(); oControl.disabled = true; }
</script>
This solution is simple and effective. On your button include this code:
OnClientClick="return CheckDouble();"
And wherever you want your JavaScript - e.g. At the bottom of your page:
<script type="text/javascript">
var submit = 0;
function CheckDouble() {
if (++submit > 1) {
alert('This sometimes takes a few seconds - please be patient.');
return false;
}
}
</script>
Most of the above suggestions failed to work for me. The one that did work was the following by tezzo:
Me.btnSave.Attributes.Add("onclick", "this.disabled=true;")
Me.btnSave.UseSubmitBehavior = False
Simpler still, rather than using the above in the code-behind, just use the following:
<asp:Button ID="btnSave" runat="server" Text="Save"
UseSubmitBehavior="false"
OnClientClick="this.disabled='true';"
</asp:button>
UseSubmitBehavior="false" is the key.
You can prevent double-clicking using this code:
Me.btnSave.Attributes.Add("onclick", "this.disabled=true;")
Me.btnSave.UseSubmitBehavior = False
So you can use btnSave_Click to call your API.
Usually I have a lot of Validators in my Page: setting Validator.SetFocusOnError = True I can run this code to reenable save button if a validation failed.
Me.YourControl.Attributes.Add("onfocus", Me.btnSave.ClientID & ".removeAttribute('disabled');")
This is the one I found works in all cases.
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Clicked" />
<asp:Button ID="Button2" runat="server" Text="Button2" />
</form>
Now here’s the short JavaScript snippet that will disable the button as soon as it is clicked so that when PostBack occurs the button cannot be clicked again.
<script type = "text/javascript">
function DisableButton() {
document.getElementById("<%=Button1.ClientID %>").disabled = true;
}
window.onbeforeunload = DisableButton;
</script>
The above script disables the ASP.Net Button as soon as the page is ready to do a PostBack or the ASP.Net form is submitted.
But in cases you might want to disable all Buttons and Submit Buttons on the page hence for such cases I have created another function which disables all Buttons and Submit buttons whenever there’s a PostBack or form submission
<script type = "text/javascript">
function DisableButtons() {
var inputs = document.getElementsByTagName("INPUT");
for (var i in inputs) {
if (inputs[i].type == "button" || inputs[i].type == "submit") {
inputs[i].disabled = true;
}
}
}
window.onbeforeunload = DisableButtons;
</script>
Prevent Double Click .Please add below code in your aspx page
<script type = "text/javascript">
function DisableButton() {
document.getElementById("<%=Button1.ClientID %>").disabled = true;
}
window.onbeforeunload = DisableButton;
</script>
At first my solution is like this:
<script>
function disableButton(btn) {
setTimeout(function () { btn.disabled = true; }, 20);
return true;
}
</script>
<asp:Button runat="server" ID="btnSave" Text="Save" OnClick="btnSave_Click" OnClientClick="return disableButton(this);" />
Without setTimeout the button will be immediately disabled and then the OnClick event will not be fired. The drawback of this approach is that the Save button will not be accessible anymore if some validation fails or some error happens.
So I don't think disable the button is a good solution, and come up with another solution:
function disableButton(btn) {
if (btn.hasclicked) return false;
btn.hasclicked = 1;
btn.onmouseenter = function () { this.hasclicked = 0; };
return true;
}
But my colleague points out that if the post processing is very slow, before it is finished, the user is still able to perform the double postback by leave-enter-click the button. So I figured out another two solutions:
Run the validation from client before submitting the form. But if your page contains multiple ValidationGroup, it is said that the following Page_ClientValidate() should be called multiple times with a passed-in ValidationGroup parameter: e.g. Page_ClientValidate("group1"):
function disableButton(btn) {
if (Page_ClientValidate) {
Page_ClientValidate();
if (!Page_IsValid) {
btn.setAttribute("btnClicked", "n");
return true;
}
}
if (btn.getAttribute("btnClicked") == "y") {
return false;
} else {
btn.setAttribute("btnClicked", "y");
return true;
}
}
As the ASP.NET has only one form in a page (not ASP.NET MVC), we can also let the onsubmit client event of the form to intercept the double click:
function disableButton(btn) {
$("form").submit(function () {
if (btn.getAttribute("btnClicked") == "y")
return false;
else
btn.setAttribute("btnClicked", "y");
return true;
});}
I'll ask QA to test those two approaches(Post edit: QA has proved that it is very dangerous to use this approach. Please refer to my following comments for details).
Try this way, it's a working solution:
For all browsers including Opera Mobile browser which doesn't support js, means your form will not be blocked in that type of browsers.
Add this in Page_load() method:
BtnID.Attributes.Add("onclick", "if(typeof (Page_ClientValidate) === 'function' && !Page_ClientValidate()){return false;} this.disabled = true;this.value = 'Working...';" + ClientScript.GetPostBackEventReference(BtnID, null) + ";");

Page_ClientValidate is validating multiple times.

problem i have is that, the validation summary message(alert) is displayed twice. I cannot figure out the reason.
Please help.
Here is the code
function validate() //javascript function
{
if (typeof(Page_ClientValidate) == 'function')
{
var isPageValid = Page_ClientValidate();
if(isPageValid)
{
}
}
}
<asp:Button ID="btn1" runat="server" OnClientClick="validate()" Text="button"
ValidationGroup="ContactGroup" />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode="List"
ShowMessageBox="true" ShowSummary="false" ValidationGroup="ContactGroup" />
The problem is that the function Page_ClientValidate takes an input parameter, if you don't specify the input then the validationsummary triggers once per groupname.
In your case, the function triggers twice: once for groupname="ContactGroup" and another time for groupname=""
you should change
var isPageValid = Page_ClientValidate();
to
var isPageValid = Page_ClientValidate('');
if you don't want to specify a ValidationGroup, or if you want to specify a groupname then you need to call Page_ClientValidate like so:
var isPageValid = Page_ClientValidate('ContactGroup');
First of all you should lose the ValidationGroup="ContactGroup" from the button because having validation group in it will first call of the validation on the page then the OnClientClick event that contains the validate function which will call the page validation once again.
Then you should pass the validation group "ContactGroup" to the Page_ClientValidate() function so it knows which controls to validate because simply calling Page_ClientValidate() will validate all controls regardless of their validation group(and it may display the validation message more than once, depending on how many validation groups you have).
In short do something like this:
function validate() //javascript function
{
if (typeof(Page_ClientValidate) == 'function')
{
var isPageValid = Page_ClientValidate('ContactGroup');
if(isPageValid)
{
//your custom code
}
}
}
<asp:textbox id="txtMyBox" runat="server"/>
<asp:requiredFieldValidator Id="rfv1" runat="server" ControlToValidate="txtMyBox"
ValidationGroup="ContactGroup" ErrorMessage="Bad!"/>
<asp:Button ID="btn1" runat="server" OnClientClick="validate()" Text="button"/>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode="List"
ShowMessageBox="true" ShowSummary="false" ValidationGroup="ContactGroup" />
just return false from the function and change the OnClientClick as shown below:
<asp:Button ID="btn1" runat="server" OnClientClick="return validate();" Text="button"
ValidationGroup="ContactGroup" />
function validate() //javascript function
{
if (typeof(Page_ClientValidate) == 'function')
{
var isPageValid = Page_ClientValidate();
if(isPageValid)
{
}
}
return false;
}
There is no need to manually call the Page_ClientValidate function, unless you're wanting to do the validation outside of a postback attempt.
Set the buttons CausesValidation to true. That'll run the validation.
You can make validation without show messages, use the following code segment,then use isPageValid variable:
if (Page_ValidationSummaries && Page_ValidationSummaries[0] && Page_ValidationSummaries[0].showmessagebox) {
var showMessagesOption = Page_ValidationSummaries[0].showmessagebox;
Page_ValidationSummaries[0].showmessagebox = "False";
isPageValid = Page_ClientValidate();
Page_ValidationSummaries[0].showmessagebox = showMessagesOption;
}
I know this is an old post, but here's a solution that may be more flexible. Similar to other users suggestions, this solution accepts the validation group that is passed by default by the asp.net validation controls. This way you would not need to add the OnClientClick="validate()" on the Button control.
//Make sure the Page_ClientValidate function exists
if (typeof (Page_ClientValidate) == "function") {
//Stash the old implementation in a temp variable
Page_ClientValidateOld = Page_ClientValidate;
//Create a new implementation and store it
//in Page_ClientValidate. Callers will now get
//this implementation.
Page_ClientValidate = function (validationGroup) {
var isValid;
//Call the old implementation first…
isValid = Page_ClientValidateOld(validationGroup);
//and then call our extension
if (!isValid) {
// Do something
}
return isValid;
}
}
If you want to read more on this approach, I recommend that you look at this blog post:
http://hyperthink.net/blog/interception-patterns-in-javascript/
Remove the click event of the button, that forces second validation I think.
remove the onclientclick event of button there is no need for that

Event isn't firing when using javascript to postback

I'm trying to use Telerik's RadSpell to spellcheck some text when the user submits it.
The way this is supposed to work is by stopping the postback, triggering the spellcheck through javascript, then in the spellcheckfinished event manually starting the real postback. The problem is that in the last step the Clicked event isn't firing for the button and the server side event handler never gets called.
Here is the relevant .aspx code:
<script type="text/javascript" language="javascript">
var spellCheckFinished = false;
var btnClicked;
function doSpellCheckStuff(btnTrigger)
{
btnClicked = btnTrigger;
var spell = GetRadSpell('<%= rsMessage.ClientID %>');
// spell.add_clientCheckFinished(checkFinished);
spell.startSpellCheck();
return false;
}
function checkFinished(sender, args)
{
args.SuppressCompleteMessage = true;
setTimeout('MySubmit();', 100);
}
function MySubmit()
{
WebForm_DoPostBackWithOptions(
new WebForm_PostBackOptions(btnClicked.id, '', true, '', '', false, true)
);
}
</script>
<tr>
<td>
<asp:Button ID="btnSubmit" OnClientClick="return doSpellCheckStuff(this);" Text="Submit"
OnClick="btnSubmit_Click" runat="server" />
</td>
<telerik:RadSpell ID="rsMessage" ControlToCheck="txtMessage" ButtonType="None"
UseClassicDialogs="true" FragmentIgnoreOptions="All"
OnClientCheckFinished="checkFinished" runat="server" />
</tr>
Any idea why btnSubmit_Click isn't getting called and how I can fix it?
Try to inject your postback script as :
string script = #"function MySubmit(){" +
this.Page.ClientScript.GetPostBackEventReference(myButton, string.Empty);
"}";
if (!this.Page.ClientScript.IsClientScriptBlockRegistered("myPostBackScript"))
{
this.Page.ClientScript.RegisterClientScriptBlock(typeof(MyPage), "myPostBackScript", script, true);
}
The last like of doSpellCheckStuff() is returning false always, which stops the OnClick event listener from running.

Resources