RequiredFieldValidator still validates when hidden - asp.net

I have 2 fields that I need to validate, if they are displayed on the screen. When the Form initially loads, they are hidden and they will stay hidden unless an item is selected from a DropDown box. Once the value is selected, the 2 fields appear and then the validation is working correctly. However, if another value is selected that doesn't make these 2 fields appear, they are still being validated and not allowing the page to submit. Any ideas on how I can achieve this?
function DisplayOutageDates() {
if ($('#ddImpact').val() == "Service Affecting") {
$('#outageDates').css('display','');
document.getElementById('txtOutageStartDate').Visible = true;
document.getElementById('RFVOutageStartDate').Visible = true;
} else {
$('#outageDates').css('display','none');
document.getElementById('txtOutageStartDate').Visible = false;
document.getElementById('RFVOutageStartDate').Visible = false;
}
}
<asp:RequiredFieldValidator ID="RFVOutageStartDate" runat="server"
ControlToValidate="txtOutageStartDate" SetFocusOnError="true"
ErrorMessage="Please enter the Outage Start Date" />

You can use :
ValidatorEnable(val, enable):
Takes a client-validator and a Boolean value.
Enables or disables a client validator.
Being disabled will stop it from evaluating and it will always appear valid.
Found on msdn.
Using Javascript this would look like:
ValidatorEnable(document.getElementById('<%=Validator1.ClientID%>'), state);
//where state would be a boolean
In JQuery this would look like:
ValidatorEnable($("#<%= Validator1.ClientID %>")[0], state);
As found here:
http://codeclimber.net.nz/archive/2008/05/14/how-to-manage-asp.net-validation-from-javascript-with-jquery.aspx

I guess you need to show and hide the Validator controls as showing and hiding the input controls.
Update
If you hide the Validator controls using display:none; They still get rendered and involved in the validation process. You need to hide them by setting the Visible property to false. This way they won't get rendered neither involved in the validation process.

Related

Parsley Validation - ASP.NET form with update panel

I am working on a legacy asp.net web forms application. I am upgrading an existing form to have a new visual style, and to use parsley validation.
We previously used the webforms validation controls, but we upgraded to parsley, as it gives a nicer user experience, and allows the control being validated to be styled when validation fails (in our case, puts a red cross graphic as the background of the input box)
The form has an update panel, for postcode / address lookup. User enters their postcode, and clicks the "Find address" button, which triggers the postback within the update panel.. I've been able to separate the two form sections (main form validation, and just the postcode input) such that user is only prompted to complete the postcode when clicking "Find Address" (using data-parsley-group="postcode" on the input box and button). I added an onclient click event to the button, to trigger the validation before triggering the onClick event of the button. See below snippets.
<asp:ImageButton ID="addressLockup" runat="server" ImageUrl="/images/btn-find-address-off.gif" class="rollover" OnClientClick="return ValidatePostcode()" OnClick="Lookup_btn_Click" CausesValidation="false" data-parsley-group="postcode" />
function ValidatePostcode() {
console.log("do postcode validaiton");
if (true === $('#aspnetForm').parsley("postcode").validate("postcode", true)) {
return true;
}
return false;
}
Now, onto my issue:
As said before, it correctly validates that the postcode has been entered, showing the red cross only in the postcode input box if that validation fails.
However, once the postcode is correctly entered, and user clicks the button, it correctly triggers the onClick event, but at this point, all the other parsley validated input boxes that haven't get been correclt filled in, show the parsley-error state (showing the red cross in my case)..I've been able to clear these once postback is complete, but you briefly see the red crosses flash, which the client won't accept..
What can I do to prevent all the other form controls showing when OnClick event fires? I'm guessing it's because it's submitting the form at this point..
Thanks for reading,
Danny
I have found a workground for this, by changing the parsley-error style before the postback occurs, and then removing the parsley-error styles from all controls, changing back the parsley-error style once page reloads:
A bit hacky, but it works.. If someone has a better solution though, it would be great to hear it!
function ValidatePostcode() {
console.log("do postcode validaiton");
if (true === $('#aspnetForm').parsley("postcode").validate("postcode", true)) {
var style = '<style type="text/css">#accountRegisterContainer input.parsley-error {background: url(""); background-color: #ffffff;}#accountRegisterContainer select.parsley-error { background: url("") ;background-color: #ffffff;}</style>';
$("head").append(style);
return true;
}
return false;
}
function pageLoad(sender, args) {
$(".parsley-error").removeClass("parsley-error");
var style = '<style type="text/css">#accountRegisterContainer input.parsley-error {background: url("/Images/parsley-cross.png") no-repeat right 10px center;; background-color: #ffffff;}#accountRegisterContainer select.parsley-error { background: url("/Images/parsley-tick.png") no-repeat right 10px center;background-color: #ffffff;}</style>';
$("head").append(style);
}

Required Field conditional on button pressed

I may be having a blonde moment here.
I have a data entry form with the usual "Save" and "Cancel" buttons. In addition to these two I have another button "Approve". If the user clicks the "Approve" button I have an additional field (Approver) that must hold data. Is it possible to have a required field validator that is active on one button press but not another?
Yes This is possible :
You can Define multiple Validation group and decide witch group to validate depending on the clicked button, for that you should call javascript function onClientClient in order to validate the inputs :
See example bellow:
Triggering multiple validation groups with a single button
I think you will have to create a custom validator or just use javascript or jquery.
You can use the OnClientClick property of the buttons and add some javascript on there.
function CheckSave() {
if (/*text1 is filled*/) return true;
}
function CheckApprove() {
if (/*text1 is filled and text2 is filled*/) return true;
}
<asp:button id='btnSave' OnClientClick='return CheckSave()' OnClick='btnSave_Click' />
<asp:button id='btnApprove' OnClientClick='return CheckApprove()' OnClick='btnAprove_Click' />
you need the return in order for it to work

Jquery validation not working after clearing a form

I have applied validation through JQuery Validation Plugin on my page. The validation works fine but once the Clear button is hit to clear out all the fields on the form, and then the save button is clicked again, the validation doesn't fire and the form gets submitted. I have called the following javascript function on click of Clear button to clear out all the form fields :-
function ResetForm() {
jQuery(':input', '#form1')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
return false;
}
The Clear button is on a ChildPage and ResetForm function is on the MasterPage. Anybody have any guess why its getting submitted after clearing the fields ?
input is an element and not a attribute or a pseudo selectable, the main issue I see in your code is the : within the :input
Try changing to jQuery('#form1 input') to fetch the list of inputs
Also change the not() command to select filter the inputs by type
.not('[type="button"], [type="submit"], [type="reset"], [type="hidden"]')
also as for :hidden there's several factors you should know about this.
They have a CSS display value of none.
They are form elements with type="hidden".
Their width and height are explicitly set to 0.
An ancestor element is hidden, so the element is not shown on the page.
In light of your comment please try this tested version:
function resetForm()
{
$("#form1").find(':input').each(function()
{
var jelem = $(this);
switch(this.type)
{
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
jelem.val('');
break;
case 'checkbox':
case 'radio':
jelem.attr('checked',false);
}
});
}
#source: http://www.electrictoolbox.com/jquery-clear-form/
Another way to do this is to create a hidden input in your form but set the type as reset like so:
<input type="reset" style="display:none" />
and then do:
function resetForm()
{
$("#form1[type='reset']").click();
}
Actually the error was something else, the code provided by RobertPitt is correct for clearing of form fields and my code was also correct for clearing of form fields. But the problem is that, on the clear button I had applied a class="cancel" so that the form should not get submitted because it was an aspx:button.
But according to what is written in JQuery docs, clicking of a button whose class is cancel should skip the validation, but after that if I click on a normal submit button validation should fire which was not firing in my case.
I just removed the cancel class and it worked.
Does this help?
Reseting the form when usering the jquery validations plugin

Using Javascript to flip flop a textbox's readonly flag

I have a frame with several radio buttons where the user is supposed to select the "Category" that his Occupation falls into and then unconditionally also specify his occupation.
If the user selects "Retired", the requirement is to prefill "Retired" in the "Specify Occupation" text box and to disable it to prevent it from being changed. The Specify Occupation text box should also no longer be a tab stop. If the user selects a radio button other than Retired the Specify Occupation text box should be enabled and once again and the Specify Occupation text box should once again be in the normal tab sequence.
Originally, I was setting and clearing the disabled property on the Specify occupation textbox, then I found out that, upon submitting the form, disabled fields are excluded from the submit and the REQUIRED validator on the Specify Occupation textbox was being raised because the textbox was being blanked out.
What is the best way to solve this? My approach below was to mimic a disabled text box by setting/resetting the readonly attribute on the text box and changing the background color to make it appear disabled. (I suppose I should be changing the forecolor instead of teh background color). Nevertheless, my code to make the textbox readonly and to reset it doesn't appear to be working.
function OccupationOnClick(sender) {
debugger;
var optOccupationRetired = document.getElementById("<%= optOccupationRetired.ClientId %>");
var txtSpecifyOccupation = document.getElementById("<%= txtSpecifyOccupation.ClientId %>");
var optOccupationOther = document.getElementById("<%= optOccupationOther.ClientId %>");
if (sender == optOccupationRetired) {
txtSpecifyOccupation.value = "Retired"
txtSpecifyOccupation.readonly = "readonly";
txtSpecifyOccupation.style.backgroundColor = "#E0E0E0";
txtSpecifyOccupation.tabIndex = -1;
}
else {
if (txtSpecifyOccupation.value == "Retired")
txtSpecifyOccupation.value = "";
txtSpecifyOccupation.style.backgroundColor = "#FFFFFF";
txtSpecifyOccupation.readonly = "";
txtSpecifyOccupation.tabIndex = 0;
}
}
Can someone provide a suggestion to me on the best way to handle this scenario and provide a tweek to the code above to fix the setting/resetting on the readonly property?
I would use jQuery instead it's super easy to implement...
To set the textbox as readonly...
$("#myTxtID").attr('readonly', 'readonly');
To set the textbox as not readonly
$("#myTxtID").removeAttr('readonly');
I recently had to do the same thing. Here's how I solved it.
go back to using the disabled property rather than readonly.
replace the RequiredFieldValidator with a CustomValidator. in your client and server validation functions, determine if you need to check the text input based on the condition of the Retired radio button. then check for input in the text box if you need to. (on the js side you can check the disabled property on the textbox itself to save yourself a step).
on the server side you should double check the radio button selection, and if "Retired" is selected, you should make sure that "Occupation" value is actually "Retired". this gets you around the issue of not getting a value from a disabled field, and you should be doing it anyway (never trust the user and all that).

How can I get value from radio-button inserted into innerHtml

I have sort of a table with a radio-button column. I managed to make radio-button column work dynamically inserting into a cell (div if matter). But, on postback innerHtml hasn't been updated with "checked" attribute.
Could you give me an idea how can I find out (on the server) if radio-button has been checked?
More info: This is on user control inside update panel.
This would be good post on my topic, still doesn't help
Any reason you cannot use a standard asp:RadioButton and use javascript to ensure it is mutually exclusive. I have done this before by adding a custom attribute to the radiobutton and then using a js function to uncheck all items with that attribute and then check the selected one. This works around the IE issue which prevents the groupname attribute from working on radioboxes that are in different containers.
radioButton.InputAttributes.Add("ClientGroupName", "grpRadioList");
radioButton.InputAttributes.Add("onclick",
string.Format(
"javascript:radiobuttonToggle('{0}','ClientGroupName','grpRadioList');"
,radioButton.ClientID));
and use the following JS to uncheck all radios and then check the one you want.
Note i used InputAttributes instead of Attributes as the radiobutton is wrapped inside a span tag so InputAttributes is for items added to the actual input control rather than the span.
function radiobuttonToggle(selectedRB, attribName, attribValue)
{
var objRadio = document.getElementById(selectedRB);
for(i = 0; i < document.forms[0].elements.length; i++)
{
elm = document.forms[0].elements[i];
if (elm.type == 'radio')
{
if(elm.getAttribute(attribName) == attribValue)
elm.checked = false;
}
}
objRadio.checked = true;
}
You can then expose radioButton.Checked as a property in your CS file and reuse this as a control.
Check Form.Request("radio-name") != null
You only get a non-null value when it's been checked.
Make sure your page elements are being rebuilt correctly on postback. Any binding process that inserted the radio buttons the first time around will have to be re-run before you can access them the second time.
Here is a working example, first I add radios to my webform by the method you linked :
function addRadio()
{
try{
rdo = document.createElement('<input type="radio" name="fldID" />');
}catch(err){
rdo = document.createElement('input');
}
rdo.setAttribute('type','radio');
rdo.setAttribute('name','fldID');
document.getElementById('container').appendChild(rdo);
}
Then at code behind I used only the code below to get the radio's value :
string value = Request["fldID"];
So, be sure you're trying to get the name of the radio buttons at server side. You should use name attribute at server side, not id.

Resources