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

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

Related

validating form in sharepoint

I developed a screen in which there are fields like first name,username,password and email. I validated these fields using javascript and came to know that javascript is not that safe. So i decided to validate on server side also. My question is whether i can use asp controls like requiredfieldvalidator, regularexpression validator to validate the form or i have to validate through server side coding??
Usually you can, it depends on how you implement the form, whether you use ASP.NET/SharePoint controls on it
You can definitely use asp controls like requiredfieldvalidator and regularexpression to validate your form. I've done this before.
Extra information
Thing to watch out for: If the page that you put these controls on is a publishing page, e.g. based on a custom layout page where editors can go in change content, the asp validator controls will still try to validate in 'Edit' mode. Therefore any SharePoint out of the box form submissions that added to the form will also trigger that the validation on your custom fields. In my case, I had a form on the page layout and some content fields, every time I edited the page, I couldn't save changes or publish until I filled out my form.
The way around it is either, stick your validator controls in EditModePanels with the PageDisplayMode set to "Display":
<PublishingWebControls:EditModePanel ID="EditModePanel1" SuppressTag="true" runat="server" PageDisplayMode="Display">
Your validator control here
</PublishingWebControls:EditModePanel>
or check for edit mode in the code behind on page load and turn the validators off from there.

Asp.Net required field validation

Hi
I need to validate two fields in an Asp.net form, where the requirements is like any one of them is required. For example, there is Page title and sub-heading input boxes, so any one of them is required. Can I do it using the validation controls Asp.Net provides?
Any kind of help is greatly appreciated. Thanks in advance.
You can use a CustomValidator control (MSDN) in ASP.NET for special situations that are not supported by any one of the other standard validators. It was created for this reason.
Microsoft describes how to create a custom validation function here.
Here's another tutorial on implementing it.
Or if you google for keywords like "creating a custom validator in asp.net" you can pick and choose from various solutions for your own project.
For your case, as an alternative to using a CustomValidator, you could explicitly change whether your required field validators are enabled by using the ValidatorEnable() JavaScript function.
// disable validation control
ValidatorEnable(RequiredFieldValidator1, false);
You can then write custom logic in JavaScript to determine the case in which each validation control is either enabled or disabled, and tie it to one of the (client-side) events of the text boxes (onblur, onchange, onkeyup, etc).
Then, on the server side you can write similar logic to do the same thing by setting the "Enabled" property and put this logic in your button click event before you check the IsValid state.
If all you are doing is conditionally determining when something is required, changing the enabled state is your best bet. Exactly what can be done is documented in ASP.NET Validation In Depth.

How to Prevent PostBack Event Handler from Firing

I have a custom class (ServerSideValidator.vb) that validates user input on server side (it doesn't use any of the .NET built in validators, therefore Page.Validate() is not an option for me). I am calling the Validate() method on page.IsPostback event and the class performs without any problem
My issue is, when validation fails (returns false), I want to stop the postback event handler from firing, but load the page along with all the controls and user-input values in them. If I do, Response.End(), the page comes up blank. I can programmatically instruct the page to go to the previous page (original form before postback), but it loses all user-inputs.
I thought of creating a global boolean variable in the page code behind file and check the value before performing any postback method, but this approach takes away from my plan to provide all functionalities inside the class itself. The page object is being referenced to ServerSideValidator.
Seems like all the postback related properties/variables I come across inside Page class are 'Readonly' and I can't assign value(s) to control/prevent postback event from firing.
Any idiea on how I can accomplish this? Please let me know if you need further details
It's probably easier to post back to the same page every time and do your validation there, specifically on the page load event. If the validation fails, you're already on the correct page and don't have to go to a previous page. If the validation succeeds, then you can redirect to another page if you wish, in which case you probably don't need any data.
Edit: This isn't exactly what you asked for, but I have a feeling it will do what you want while fitting into the existing ASP.NET validation design. See http://www.dotnetcurry.com/ShowArticle.aspx?ID=197 and https://web.archive.org/web/20211020145934/https://www.4guysfromrolla.com/articles/073102-1.aspx
Basically, you create a custom class just like you have now, but inherit from BaseValidator. To follow your design, you can create an enum called ValidationType which has Alphabetic, Alphanumeric, etc. In your custom class, create a property called ValidationType that uses the ValidationType enum. Of course you have to add all the validation logic. Then in your aspx page, you can add your custom validator to the page and set ValidationType="Alphabetic", etc. with full IntelliSense support.
Since you use BaseValidator, all the regular validation techniques will work including Page.Validate(), Page.IsValid, etc. You can even create client-side validation JavaScript if you wish.
Having said this, someone has probably already done most of this for you.

Using JSON or postback method?

I need to develop a page which has 2 dropdownlist.
Options of dropdownlist 2 are based on selection of dropdownlist 1.
I have 2 methods to change the dropdownlist 2. What will you choose?
1:
Postback when users select dropdownlist 1 and change dropdownlist 2.
Pros:
Can use the postback feature, can use the asp.net validator
Cons:
Need to communicate with server (more traffic)
Users will see the page loading in the status bar.
2:
Get all the data (not very much data) in a JSON object when loading the page and change the dropdownlist 2 using javascript.
Pros:
Don't need to communicate with server(less traffic)
Cons:
Can't use the postback feature and validator and more troublesome to write server validation.
Also, I usually write the JSON object to the page as follows:
var locations = <asp:Literal runat="server" id="litLocation" text="[]" />
And then set the "litLocation" in page_load after the data is processed by datacontractjsonserializer.
Do you do it in the same way?
I prefer the second option, no need to reload the whole page just to refresh one dropdown list. I'd also do the client side dev in jQuery, much easier. You can do the client side validation for the change event of the first dropdown in jQuery as well, and keep the form submit validation in ASP.NET.
Have a look at the selectChain plugin for jQuery (demo's etc here).
Why not have your javascript call the server when the select box is clicked on, using a GET method, and fill in the select box, using json as the response, then, when an option is picked then fill in the second select box with another ajax request.
This would be scalable, in that if you want to add more options you just change the server, and everything is centralized.
You will need to validate when the form is submitted anyway, as it is possible to change a value of a form to something illegal using some debugging tools, such as Firebug, so never trust anything from a webpage until you have validated it.
So, no point worrying about the validation until the form is actually submitted.

Is is possible to get ASP.NET input controls to act like a basic HTML Form?

ASP.NET has a number of nice features regarding making data input pages:
Adding input controls is easy (<asp:...).
The system automatically generates member variable for the controls.
Post-backs automatically populate the members variable with the returned values.
and some not so nice bits
post-backs seem to be tied to JavaScript for even the simplest of cases. For instance, with statically defined pages, using only basic controls, that are known at compile time.
My questions:
Is is possible to get the first list without the second?
What features does that JavaScript give the user?
What does that JavaScript actually do?
What is the technical reasons that it's used even in trivial cases?
As it happens my assumption were in error: See here
It really depends on the types of controls you are trying to use here -- the only ones that implement javascript are those that can't natively cause a postback (ie, an input/submit button are the only two that can). If you are using a LinkButton, ImageButton, or anything that you set "AutoPostBack = true" on will turn javascript on in order to cause a postback.
Other controls can also potentially use javascript if they are more advanced such as the Calendar. The technical reason for using javascript here is to provide automated postback when the controls require more advanced server interaction -- think about it, a link is meant to only ever be a link and if we're trying to make it operate as a button we have to force it to do just that through javascript interaction.
So that being said, yes you can definitely use ASP.NET without it having javascript you just have to avoid the controls that implement it by including functionality you couldn't possibly have without it. You can just as easily add HTML controls and add the runat="server" attribute and gain member variables to the control from code-behind.
Here's what came to my mind:
What features does that JavaScript give the user?
Client side validation.
What does that JavaScript actually do?
For exmaple, it ensures that the correct (server-side) event handlers are called, by setting the __EVENTTARGET hidden field.
Is is possible to get the first list without the second?
You can use normal HTML controls instead of the ASP.NET controls. Then on the server-side, you can read the control's values from the Form collection.
I assume you mean the javascript associated with an <asp:Button /> control, right?
In addition to the reasons mentioned by Fooberichu, the javascript can also help with ASP.NETs client side validation framework.
But I think it's primary use is to alert the framework what events it should fire on the postback in the page behind.
So if you had two buttons on the form, SaveButton and DeleteButton, the javascript helps the framework know whether it should execute the SaveButton_Click event or DeleteButton_Click event.
Hope this helps.

Resources