Ron
Ron

Reputation:

Question about javascript alert asp.net c#

I'm working on a web page that saves in user information on a button click and then redirects the page.

However, I want to alert the user if he/she forgets to fill in a value in one of the controls. and ask to correct the error and click the save button again..

I implemented a similar function with confirmbox but since the alert box does not have a return value I was wondering if such an implementation is possible?

Upvotes: 0

Views: 1282

Answers (5)

Juri
Juri

Reputation: 32900

Instead of going to validate with custom JavaScript and alert boxes, try to reuse the standard ASP.net validation controls. There are a bunch of them available for required fields, comparison validators, custom validators etc. The advantage is that you use standard mechanisms and that you can access them for doing server-side as well as client-side validation. The server-side validation is important if your user has JavaScript disabled in his browser which still seems to happen.

Moreover I actually prefer that things happen directly on the page and not with alert boxes (this is somehow the old way of doing things). Alert boxes lower the user experience since he continuously has to click it away and moreover he has to read what happened, while if the error is shown directly beneath its source makes it easier to see (just from a usability point of view).

You could alternatively also look at the jQuery validation mechanism. As far as I know there exists one.

Upvotes: 1

ChaosPandion
ChaosPandion

Reputation: 78262

Server Side

<asp:Button ID="MyButton" runat="server" OnClientClick="return myFunction();" OnClick="MyButton_Click" Text="Save" />

Client Side

function myFunction() {
     if (document.getElementById("<%=this.MyFieldName.ClientID%>").value.length == 0) {
         alert('Please fill in the field.');
         return false;
     }

    return true;
}

Upvotes: 1

user167282
user167282

Reputation:

Or you could change the text in your alert box to a question and use a confirm box instead:

if (document.getElementById('myTextBox').value == "")
{
    return confirm('Are you sure you want to exit without filling in ... ?');
}

Upvotes: 0

Matt Hamsmith
Matt Hamsmith

Reputation: 4016

You can also use a asp:RequiredFieldValidator tag and let the ASP.Net validation logic do all the checking and user prompting for you.

Upvotes: 1

womp
womp

Reputation: 116977

I don't think you need a return value. Your function can cancel the button submission by just returning false.

function myBtnClick()
{
   if (document.getElementById("myTextBox").value == "")
   {   
      alert("You forgot to fill it in!");
      return false;
   }

   return true;
}

Upvotes: 0

Related Questions