How to make ASP.Net custom validators produce an alert - asp.net

All ASP.Net client validation messages can be shown as an alert by setting the ShowMessageBox="True" property on the ValidationSummary control.
This works fine for anything that happens on the client.
For the custom validators that validate server-side I had assumed that what would happen is that when the page is returned to the browser, ASP.Net would inject some javascript to show the alert box. However this isnt the case.
If you had relied on the message box to show detail and just have a * next to the erroneous field (as per my clients req's) then it wont work as intended.
Does anyone have a solution for doing this? What I want is a way to possibly override the ValidationSummary control to inject javascript onto the page or something like this.
Thanks in advance.

You may use Page.RegisterStartupScript to show alerts after server-side validation.

Related

How ASP.NET 4 validation controls work?

I create new page with lots of validation controls, such as RequiredValidation, RegexValidation and so on. I found out that when I create these validation controls, it seems like it render both client java-script and server validation for me automatically.
I want to know, do I understand correctly or not?
Yep. That is correct. The built-in controls do server side validation (for security) and client side validation (for performance and user experience) for you.
Tip: Don't add these validations to the mark-up, but add them through the code behind, as shown in this blog post, since it keeps your code DRY.

How to trigger ASP.NET client-side validations without submit?

I have a website in ASP.NET (WebForms, NOT MVC) which has a survey form divided in several slides. Each slide has a next button that, obviously does a transition (client-side, not post back or remote request) to the next slide.
In each slide I have several ASP.NET controls with their related validators. I want this validators to be triggered when I click the next button (or maybe when each input loses focus?).
I remembered ASP.NET doing client side validation on lost focus, but maybe I'm wrong... (I quit doing ASP.NET development about 3 years now, so I can't remember)
Thanks
UPDATE:
It would be better to make ASP.NET trigger each validator when the associated control lost focus. I remember ASP.NET doing this (or am I dreaming? =P)
First you need to make sure all of your validators have target controls specified using the "TargetControlID" Attribute on the validators.
Then you can set up a validation group per page and specify the group name in your next button and on the controls themselves.
If you are using regular expression validators you can choose them from this website
To Validate Client Side
If you are using custom validators you can create a client function and specify it on the custom validator using the ClientValidationFunction attribute and by setting EnableclientScript = "true" on the custom validator.
Just be sure your client function has sender and args parameters.
It looks like there's a supplied JavaScript function called Page_ClientValidate which should be callable to check the validation manually from JavaScript. I haven't used it, though, so YMMV.
put all your client-side validators into the same validationgroup and with your 'next' button add the same validation group. When you click the button it will automatically trigger all the validators before it does the post-back.
as to manually triggering the validation...
you might also be able to use ValidatorOnSubmit(). I remember doing this in another project but i'm having a hard time finding the code.
It seems that enabling 'SetFocusOnError' on each validator triggers the validation whenever I try to leave the field.
In short decorate your model, now Data Annotations are supported from Asp.Net 4.5
Check my Answer here..Client side webform validations

How do I display an error message in asp.net?

I have a bunch of text boxes and a save button to update something. When I click Save I have code that determines whether they are correctly filled in, in the code behind file.
If they are not correctly filled in, I want to display an error message in the form of an alert.
What is the best way to do this? Pressing the button obviously makes the page postback, so I thought about adding something to the URL like mypage.aspx?errormessage=blahblah but I don't know if this is the best way or even how to do it...
Any suggestions?
Modal alerts are bad, as are postbacks. Try to check as much as possible on the client-side without a round-trip to server. See jQuery Validation plugins for a less intrusive way of validation.
Could you use a CustomValidator to trigger client side script that shows a alert box?
You could use the ClientScript.RegisterStartupScript() method in the server side error handling code to write a javascript snippet which calls alert('message'), something like this
private void ShowErrorMessage(string message)
{
string script = "alert('" + message + "');";
ClientScript.RegisterStartupScript(typeof(MyPage), "errorScript", script, true);
}
But I would recommend you use a validator instead. If you implement your own custom validator, you can make it emit client-side script which can run before the submit, to avoid the postback altogether.
A good thing about validators is that their error messages can be displayed in a ValidatorSummary on the page, avoiding the ugly alert box.
First of all I won't recommend showing an modal alert box to the user.
You can call a javascript function from the server side code and in that function you can pop out the error.
Or you can issue an AJAX request and after the validation on server side you can send back a response to the client.
ASP.NET's various validation controls (with client-side validation enabled), coupled with proper error messages and/or summary message will be good enough for most scenarios.
For 'AJAX feel and behaviour', put the controls into an updatepanel will be easy to implement too.
Use ye olde Validators as much as poss, they render out some javascript to the client so yu can do alot of validation using these controls and only when they are all satisfied does it allow the page to submit.
They do fire on every submit so if you don't want every submit action to fire them you make the controls part of a validation group.
They can validate input using regular expressions, make sure a field has a value and there is a few more as well.
Then there is property to declare a 'message' and a control to show all the validator messages. All very swish and built right into the IDE.
Go check out the validator controls.
Try the following code in your button click event:
string strErr="Error!";//Put your error message here
ClientScript.RegisterStartupScript(GetType(), "scrptName", "javascript: alert('"+strErr+"'); ", true);
It will show an alert message.
Else put a label on your aspx page and set visible false in page_load event.
When error occurs in your button event set the label visibility 'true' and fill the label text with the error message.

JQuery with asp.net 3.5 and doing post/call backs

I currently have a simple form that when you click the "save" button will persist it to the database.
I would like to use JQuery to do the callback for me and popup a "Save completed" div window/div of some sort.
My only problem is how do I call the btnSave_Click() event from JQuery?
If I use PageMethods the method would have to be static and therefore lose access to my textboxes and other page controls?
Thanks,
Goosey
Are you explicitly trying to avoid passing the values of the input controls? because that would be much easier.
Using a lightweight jQuery call to do the post but then expecting a full control hierarchy in the code behind to pull data out? What's the intent here? If you require that, it would probably be easier just to submit the page, and register javascript to run to pop the success message up on load.
Personally, I think the page method route and $.ajax or $.post is a much cleaner, separate way to solve the issue. That way you can just show the popup as part of the success callback.
You can use onClientClick
Have a look at the jQuery Form Plugin, it can change existing forms into Ajax forms.
You need to set __EVENTTARGET to the id of the control that you want to simulate causing the postback if you want to use the same handler. I seem to recall having to replace the underscores with dollar signs as well, but I could be wrong on that. The hidden inputs, __EVENTTARGET and __EVENTARGUMENT, are used by the framework to identify which control caused the postback. There's a nice discussion of the server side issues in this blog post, though it doesn't talk about AJAX. Google for __EVENTTARGET and postback for more info.

Problem with Asp.Net RequireFieldValidator and Javascript WYSIWYG

I am using the open source Javascript WYSIWYG from OpenWebWare and Asp.Net RequiredFieldValidator on the TextBox which I am calling the WYSIWYG for. Everything works fine, but the first time I try to submit the form, I get the server-side RFV ErrorMessage "Required", but if I submit a second time, it goes through.
Am I missing something? I would like to have the client-side validation... how can I get the text to register as not empty?
I think the reason for this behavior is that validation code runs earlier than the code that updates underlying TextBox from value of WYSIWYG. So the first time you get the error, then the field is updated and the second time you don't get it. Try removing all the content the second time and I bet you wont get validation error (since the value for validator at the moment is what you actually submitted the first time).
The solution would be to find a JavaScript API call for your WYSIWYG which would force the update of the underlying text box field and call it onclick (client-side) of your submit button or whatever you use for that.
the textarea HTML tag is one of the most unpleasent tags to work with and I'm not 100% sure if the client-side validator will support it, regardless of whether it's a WYSIWYG or not.
I think you'd be best off using a CustomValidator and writing the JavaScript which does the checking manually.
Alternatively you can debug though the JavaScript which is used with FireBug or VS 2008.

Resources