ASP.NET form validation - highlight fields with JS/DHTML - asp.net

I have an issue that's been bugging me this morning. I'm building an ASP.NET webforms app that has many input forms and I'm trying to standardise how I manage validation. I would like to use the built-in validators (RequiredFieldValidator, Regex etc). My html requirements are:
Before validation:
<div class="formLine">
<label for="fieldID">Form Label</label>
<input type="text" id="fieldID" />
</div>
After validation (in case of error):
<div class="formLine formError">
<label for="fieldID">Form Label</label>
<input type="text" id="fieldID" />
<span class="errorMessage">Please enter some value</span>
</div>
The additional span is fine, this is achieved with the ASP.NET validation controls. My problem is adding the formError class to the containing <div>.
I'm comfortable using jQuery/DHTML to add this class, but just don't know where to hook it in. Is it possible to monitor DOM changes with jQuery - for example fire an event handler whenever a span is added as a child of <div class="formLine">?
Does anyone else have any good suggestions for dealing with this?
Thanks for reading.

EDIT: After clarification
You could write a custom function that is called by the onClick client side event. Because you are using ASP.Net validation controls you should be able to call the function ValidatorValidate(val) where val is the validator. You could then check the contents of the validators SPAN tag for your validation error and update your div tag accordingly.
Note: I'm no expert on client side validation but this should work in principal.
Further info on MSDN.
You need to declare your div as runat="server" with an id tag so you can reference it in server side code then in page load do a test for Page.IsValid which will return false if one of your validators fails to vaildate.
You can then set the class property on your div programatically. Something like:
<div class="formLine" id="divForm" runat="server">
<label for="fieldID">Form Label</label>
<input type="text" id="fieldID" />
</div>
Code-Behind (VB)
If Not Page.IsValid Then
divForm.Attributes.Remove("class")
divForm.Attributes.Add("class", "formLine formError")
End If

i'm assuming you're looking for a way to do this on the client side, without postback.
when you use asp.net validation controls on your webform you'll notice that a script reference to WebUIValidation.js is rendered on your page. peeking into that file offers some useful info. there's a global variable in that file named Page_IsValid. whenever validation fails, that variable is set to false.
EDIT: the WebUIValidation.js script reference was prior to .net 2.0, so you can't look at that file anymore. however, the Page_IsValid variable is still there and can be used by hooking into a form submit handler. something like this
// verified that this works
$(document).ready(function() {
$('#form1').bind('submit', function(e) {
if (!Page_IsValid)
$('#yourDiv').addClass('error');
});
});

Related

can I run multiple server side forms in asp .net

In my project I want to run 2 forms in one webpage which is master page one is for contact us and one is for signup user. but multiple server side forms are not allowed. is there any solution for fix it?
You can use postback ability of Asp.net Webforms.
You should create one button for singup and another one for contact. You can catch event in server side and you do what want to do.
You can create regular client side forms created using HTML in the master page, and use the Request.Form to read the posted data. For this to work, all the input elements must have a name, and you can read them using Request.Form["ElementName"].
Take into account that forms cannot be nested.
So, your master page needs to llok like this
...
<body>
<form id="form1" runat="server">
</form>
<form id="contact" action="Contact.aspx" method="post">
<input type="text" name="Message"/>
<input type="submit" value="Contact us!"/>
</form>
</body>
The first <form> is the regular ASP.NET server side form, which supports server side components
The second <form> is a custom HTML form. It doesn't have the runat="server" attribute, and it's outside the server side <form>.
The second form action points to a .aspx page. In its page load event you can use the Request.Form["Name"] to acces the name of the contact form. Note that you also need to include a submit button to send the data to the server, and a method="post" to specify the method to send the page.
This is resorting to "basic" HTML controls, so there is no View State, and the posted values will be lost if they're not reset in the server. I.e. if the form is posted, and there's an error, the previously posted values will be lost when rendering the page again.
If you want to make it more sophisticated you can use Javascript and, optionally AJAX. But that's a more complex solution. See this for an example.
ASP.NET Forms only supports one form. You could use an iFrame and render your second page (second form) inside of the iFrame.
Here is an interesting post about placing some page content after the tag. This may be helpful to you.
http://forums.asp.net/t/1611822.aspx?Dynamically+adding+content+to+page+outside+of+the+aspnet+form+from+within+a+UC

Calling server-side function from HTML on click (Classic ASP)

I am trying to use my if else statement inside my Function Save() but I cannot make it works? After click on the img button I want to verify if mycheckBox_A is checked. By the way I am using classic ASP
<img src="blah" onclick="<%Save()%>"/>
<%
Function Save()
If mycheckBox_A.checked Then
'mycheckBox_A is checked
Else
'mycheckBox_B is checked
End If
End Function
%>
The onclick attribute is not for calling server-side functions. You can assign JavaScript to this one, but not VB function. Think if you really need server-side code here that's possible that all you need in this exact place could be done with JavaScript.
EDIT:
If you need to do something on the server, you have to use AJAX to send only data you want to the server or submit the form with submit button or JavaScript call to submit() method. After submitting date you have to process it in your server-side function. Check this short tutorial on processing submitted with both POST and GET methods.
According to how to call a ASP function in the onclick event:
ASP functions execute only on the server side, while the onclick event
executes only on the client side. You are trying to mix the two in an
impossible way.
The problem is that the function calculate() does not exist on the
client-side. The browser cannot see it.
You will need to use JavaScript (or another client-side technology) if
you want to have this type of functionality.
This also applies to your Save() function.
You can't use onclick like this. Your only option is to have the button be either a submit button, or a link, then handle it on postback (if you need to do it server-side) or to write it in javascript if it can be done client-side.
Using postback to handle server logic is quite simple and basically how it works in modern ASP. You could have the submit button be in a form which has an integer, showing what you want to do, then handle this at the top of the page. That way, you can postback to the same page, handling different kinds of logic depending on what button was pressed, etc.
Should be noted that this makes for pretty ugly code, but then again, it's classic ASP.NET, it will look ugly no matter what.
No need to use any client script here at all
<%
'Have you POST to this page?
If Len(Request.Form) > 0 Then Call Save()
Sub Save()
Dim a_check, i_item, i_items
a_check = Split(Request.Form("checkbox") & "", ",")
If IsArray(a_check) Then
i_items = UBound(a_check, 1)
For i_item = 0 To i_items
'Could store this and output it later on but is just a quick example
Response.Write a_check(i_item) & " is checked"
Next
End If
End Sub
%>
<html>
<head>
</head>
<body>
<!-- make the page POST to itself -->
<form method="POST" action="">
<! -- your other fields etc
<input type="checkbox" name="checkbox" value="A" />
<input type="checkbox" name="checkbox" value="B" />
<input type="submit" value="Save" />
</form>
</body>
</html>
Quick example nothing special untested.
You can use JQuery post method and pass your variables to classic asp page.

Checking a radio button with jQuery when radio button is runat="server"?

Using jQuery I want to be able to click an element which will also checks it's related radio button. I had this working fine until we had to add runat="server" to the radio buttons.
When I apply this it prevents my jQuery function from working and I cant figure out how to get round it, heres a simplified version of the code:
HTML
<input type="radio" runat="server" id="sector1Radio" name="SectorGroup" title="Sector1" />
jQuery
$('#SomethingElse').click(function() {
$('input[title=Sector1]').attr('checked','checked');
});
I've found out that when its converted to a .net control instead of checked="checked" (as it would be usually) it is just Checked, so I changed that but on inspecting the DOM in multiple browsers, none of my radio buttons are being checked :-(
Are there any other ways I can use jQuery to check a radio button that has runat="server"?
Cheers!
I think that Your problem is that the id of the input is no longer sector1Radio but rather ctl00_sector1Radio or something similar. This happens if Your input control is inside e.g. a ContentPlaceHolder control (when using master pages).
Can You check the generated HTML code (in the browser) to verify if this is the case? What is the id of the input control?
If this is the case, You need to generate Your js jQuery code
$('#SomethingElse').click(function() {
$('input[title=Sector1]').attr('checked','checked');
});
from codebehind so that SomeThingElse is replaced with the ClientID of the control.
.is(':checked') works on ASP.NET radiobuttons and checkboxes
$('#SomethingElse').click(function() {
$('input[title=Sector1]').is(':checked');
});
try using
$('input[title=Sector1]').attr('checked',true);
and
$('input[title=Sector1]').attr('checked',false);
or maybe
$('#SomethingElse').click(function () {
$('input[title=Sector1]').attr('checked',!$('input[title=Sector1]').attr('checked'));
});
As suggested by others, ASP.net will not generate the html with the same ID you specified.
Quick solutions:
You can keep using the id but asks jquery to check the end of the id instead, example:
$("input[id$='sector1Radio']").is(":checked");
Or check against the title and name as Nico suggested
Use the class element which is not effected by ASP.net, example
<input type="radio" runat="server" id="sector1Radio" class="sector1Radio" name="SectorGroup" title="Sector1" />
$("input.sector1Radio").is(":checked");
Best thing is to view the generated html code and see what id is giving you, then you can use the appropriate jquery selector, because the generated id could have different extensions depends whether you use master pages, etc.
If you are using a MasterPage or are creating the controls dynamically then it is probable that the control ID's are being renamed #SomethingElse becomes #MainContent_SomethingElse.
The easiest way to check this is to use the WebDeveloper plugin for Firefox or Chrome.
Go to Information -> Display Element Information and then select the object in question. It will give you it's ID, class, as well as ancestor and children information.
Check to see if the ID is being changed dynamically by the .NET.
If that's the case:
To prevent this, in the server side code you can use the following attribute to create static ID's
SomethingElse.ClientIDMode = ClientIDMode.Static;
You can then reference in you jQuery
$('#SomethingElse').click(function() {
if ($('input[title=Sector1]').attr('checked')) {
//execute event
});
I think what happens is that in ASP NET Checkboxes and Radio Buttons generates an "input" and a "span" after the input. So you need to select the input only.
You can try:
$('.classname input[type=checkbox]').each(function() {
this.checked = true;
});
Two things here: finding the control and executing the check. In ASP.NET, your control's actual ID and name will end up getting changed based on the runat="server" containers in which it appears, even if those containers have no Ids.
Rendered ASP.NET controls always end with the same name as you started with, so a tag like:
<input type="radio" runat="server" id="sector1Radio" title="Sector1" />
might end up being rendered as
<input type="radio" runat="server" id="ctl0$ctl0$sector1Radio" name="ctl0_ctl0_SectorGroup" title="Sector1" />
You can find this element, even after it is rendered if you use the "contains" selection syntax in JQuery. So to find this element, once rendered, you could use:
$("input[type='radio'][id*='$sector1Radio']")
This syntax will find any radio button whose id contains "$sector1Radio"
Once you have the element, you can check or uncheck it using the following code, which you'd call from the click event of your other element.
// check the radio button
$("input[type='radio'][id*='$sector1Radio']").attr('checked', true);
// uncheck the radio button
$("input[type='radio'][id*='$sector1Radio']").attr('checked', false);
One last thing... if you just want a block of text to click the button when pressed (wrap it in an tag and set the AssociatedControlId property to the control name of your radio button, like this...
<input type="radio" runat="server" id="sector1Radio" title="Sector1" />
<asp:label runat="server" id="lblsector1Radio" associatedControlID="sector1Radio">clicking here clicks and unclicks the radio button</asp:label>
I had the same problem. To use the jQuery UI to make your radiobuttons nice one has to write:
<div id="radio">
<input type="radio" id="radio1" runat="server" />
<label for="radio1">The label of the radio button</label>
...
</div>
<script type="text/javascript">
$('#radio').buttonset();
</script>
The id of the input tag must be correctly referenced by the label's for attribute. If the webpage is inside a master page then the id of the input tag will be modified to something like ctl00_Something_radio1, and suddenly the label's for attribute no longer references the input tag. Beware of this in ASP.NET!

ASP.NET 1.X to ASP.NET 2.0: Broken Validation on Postback

Good Day,
We have migrated our web application to ASP.NET 2.0 from ASP.NET 1.1.
We have a page that contains a couple of textboxes with their respective Validators.
On .NET 1.1, when a textbox contains an INVALID value, clicking on the "submit" button, will not produce a postback (E.G. Nothing will happen).
However, when we migrated to .NET 2.0, even if there is an INVALID value, the postback will still happen. (E.G. Pressing the "submit" button will perform a postback).
Is there an issue with validation when migrating from 1.1 to 2.0?
Additional Infos:
The "submit" button is an input button:
<input type="button">
Using an <asp:button> in place of the <input> button will work and will fix the problem. However, the <input type="button"> has the capability to call a javascript that will produce a "Wait... Loading" label overlay on the page. Using the asp:button, the "Wait... Loading" overlay javascript will NOT be invoked.
EDIT: Real problem and solution.
Anyway, the real problem is that the on-click validation javascript was broken during migration.
The original and working script is:
<input language="javascript" onclick="{if (typeof(Page_ClientValidate) != 'function' || Page_ClientValidate()) __doPostBack('m_bt_Save','')} " name="m_bt_Save" id="m_bt_Save" type="button" value="Save" width="80px" height="24px" />
But ASP.NET 2.0 changed it to:
<input onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(''); __doPostBack('m_bt_Save','')" name="m_bt_Save" type="button" id="m_bt_Save" value="Save" width="80px" height="24px" />
So the my solution was, change the INPUT button to an ASP:button, then add the attribute doing page load with the correct ASP.NET 1.1 javascript validation like so:
m_bt_Save.Attributes.Add("OnClick", "if (typeof(Page_ClientValidate) != 'function' || Page_ClientValidate()) __doPostBack('m_bt_Save','')");
One thing you can do, is you can just add your JS that you need to the button.
Button1.Attributes.Add("OnClick", "do my js stuff here");
That will allow you to have the exact same functionality as the input, and it makes it work.
Otherwise, my guess is that you will need to modify the way the input button submits to call the validate page method before it does the from submit.
You can use page validators from the javascript.
See this link:
http://www.aspdotnetfaq.com/Faq/How-to-control-ASP-NET-Validator-Controls-Client-Side-validation-from-JavaScript.aspx
http://www.codedigest.com/Articles/ASPNET/166_Restrict_AspNet_Validator_controls_to_Fire_on_Page_Submit.aspx
This happened in our upgrade as well. I think we narrowed it down to a problem with the WebUIValidation.js file. I think re-installing it was the final fix for us.

When does an HTML input tag post back on enter?

I have a couple of asp.net pages with TextBox controls on them. Some of them postback on enter (within a TextBox control) and others don't. For the life of me, I can't figure out why or why not...
I don't think this has anything to do with asp.net. Not using ajax etc. Tried playing with a very simple html page and still can't figure it out.
Maybe within or not within a <form> tag? But all my asp:textbox controls are within the standard form tag and some do and some don't. Not related to autoPostback from what I can see.
EDIT:
Sample markup which causes a post back:
<html>
<body>
<form>
<input type=text />
</form>
</body>
</html>
I have asp.net pages that definately don't post back. The code is extensive and I can't figure out why not.
EDIT2:
How can I prevent a postback?
If you only have one textbox and don't wan't this behavior, you could always put a hidden input on the form.
<html>
<body>
<form>
<input type="text" ></input>
<input type="text" style="visibility:hidden"></input>
</form>
</body>
</html>
I've tried this in IE7 and FF3 and it works.
Generally most web browsers will detect when a form has only one textbox and will automatically submit the form when enter is pressed.
If you have multiple text boxes or multiple form buttoms, the behaviour varies. ASP.Net has the "defaultButton" mechanism for buttons, meaning you can specify which button is the submit button for a given panel in the case of the enter key being pressed. You could check out this post for more information on setting up your forms to correctly post back.
As Boo mentioned, this won't be triggered by multi-line textboxes.
If the behaviour is really crappy in your form between browsers, you may need to look at a javascript solution to catch the enter key being pressed, and "manually" submitting the form via javascript.
If the textbox control is set to autopostback it will postback on every keypress (thus allowing the firing of the TextChanged event).
Next, text boxes that have their Multiline property set to false will appear to postback on Enter.. what is actually happening is a form submit as defined by the behaviour within the browser.
Boxes that have Multiline set to true will not cause a form submit on Enter.

Resources