Parsley Validation - ASP.NET form with update panel - asp.net

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);
}

Related

RequiredFieldValidator still validates when hidden

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.

how to solve that a page is not postback even all validation is validated using jquery validation engine on sharepoint server 2007?

I have complex form and in page a submit button, it has events for both client and server side.
After first time clicking on button, validation class is added and then validation error message is shown,
and then filling to a required field to be validated, and click on button again, page is not post back, even jquery validation engine works well.
In my local computer, page is postback after filled to a required field. I assume, both client side and serverside work.
But not on sever, page is not post back after filled to a required field.
This is my code. I am looking forward your replies and suggestions.
==========================================================================
jQuery(document).ready(function () {
jQuery("#aspnetForm").validationEngine();
//btmContinous
$('#ctl00_PlaceHolderMain_Form1_btmContinous').click(function () {
//Part A
var className = $('#ctl00_PlaceHolderMain_Form1_txtA2').attr('class');
alert(className);
if (!(className == "validate[required] text-input"))
{
alert(className);
$('#ctl00_PlaceHolderMain_Form1_txtA2').addClass("validate[required] text-input");
}
if ( $("#Form1").validationEngine('validate') == true) {
alert("true");
//$('#ctl00_PlaceHolderMain_Form1_txtA2').removeClass("validate[required] text-input");
//should post back here
}
else{alert("false");}
});
It was yesterday i was having the same issue. My validation will not work after postback.
Page contained update panel and all validations on button click inside document.ready.
The validation will not work after postback.
What i did is put the validation i.e
$("#<%= Button1.ClientID %>").click(function() {
//// Validation conditions here
});
inside the Sys.Application.add_load() function and it started working after postback too.
So now code looked like
Sys.Application.add_load(function() {
$("#<%= Button1.ClientID %>").click(function() {
//// Validation conditions here
});
}
More about what happens can be read here
http://www.codeoutlaw.com/2009/11/use-sysapplicationaddload-instead-of.html
Hopefully this helps someone :)

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

How do I clear MVC client side validation errors when a cancel button is clicked when a user has invalidated a form?

I have a partial view that is rendered within a main view. The partial view takes advantage of System.ComponentModel.DataAnnotations and Html.EnableClientValidation().
A link is clicked, and div containing the partial view is displayed within a JQuery.Dialog().
I then click the save button without entering any text in my validated input field. This causes the client side validation to fire as expected, and display the '*required' message beside the invalid field.
When the cancel button is clicked, I want to reset the client side MVC validation back to it's default state and remove any messages, ready for when the user opens the dialog again. Is there a recommended way of doing this?
This answer is for MVC3. See comments below for help updating it to MVC 4 and 5
If you just want to clear the validation-messages so that they are not shown to the user you can do it with javascript like so:
function resetValidation() {
//Removes validation from input-fields
$('.input-validation-error').addClass('input-validation-valid');
$('.input-validation-error').removeClass('input-validation-error');
//Removes validation message after input-fields
$('.field-validation-error').addClass('field-validation-valid');
$('.field-validation-error').removeClass('field-validation-error');
//Removes validation summary
$('.validation-summary-errors').addClass('validation-summary-valid');
$('.validation-summary-errors').removeClass('validation-summary-errors');
}
If you need the reset to only work in your popup you can do it like this:
function resetValidation() {
//Removes validation from input-fields
$('#POPUPID .input-validation-error').addClass('input-validation-valid');
$('#POPUPID .input-validation-error').removeClass('input-validation-error');
//Removes validation message after input-fields
$('#POPUPID .field-validation-error').addClass('field-validation-valid');
$('#POPUPID .field-validation-error').removeClass('field-validation-error');
//Removes validation summary
$('#POPUPID .validation-summary-errors').addClass('validation-summary-valid');
$('#POPUPID .validation-summary-errors').removeClass('validation-summary-errors');
}
I hope this is the effect you seek.
If you are using unobtrusive validation that comes with MVC you can simply do:
$.fn.clearErrors = function () {
$(this).each(function() {
$(this).find(".field-validation-error").empty();
$(this).trigger('reset.unobtrusiveValidation');
});
};
------------------------------------------------------------------------
Third Party Edit:
This mostly worked in my case, but I had to remove the $(this).find(".field-validation-error").empty(); line. This appeared to affect the re-showing of the validation messages when resubmitting.
I used the following:
$.fn.clearErrors = function () {
$(this).each(function() {
$(this).trigger('reset.unobtrusiveValidation');
});
};
and then called it like this:
$('#MyFormId input').clearErrors();
function resetValidation() {
$('.field-validation-error').html("");
}
You can simply define a new function in jQuery:
$.fn.resetValidation = function () {
$(this).each(function (i, e) {
$(e).trigger('reset.unobtrusiveValidation');
if ($(e).next().is('span')) {
$(e).next().empty();
}
});
};
and then use it for your input fields:
$('#formId input').resetValidation();
Thank you. I had a similar question for a slightly different scenario. I have a screen where when you click one of the submit buttons it downloads a file. In MVC when you return a file for download, it doesn't switch screens, so any error messages which were already there in the validation summary remain there forever. I certainly don't want the error messages to stay there after the form has been submitted again. But I also don't want to clear the field-level validations which are caught on the client-side when the submit button is clicked. Also, some of my views have more than one form on them.
I added the following code (thanks to you) at the bottom of the Site.Master page so it applies to all of my views.
<!-- This script removes just the summary errors when a submit button is pressed
for any form whose id begins with 'form' -->
<script type="text/javascript">
$('[id^=form]').submit(function resetValidation() {
//Removes validation summary
$('.validation-summary-errors').addClass('validation-summary-valid');
$('.validation-summary-errors').removeClass('validation-summary-errors');
});
</script>
Thanks again.
You can tap into the validation library methods to do this.
There are two objects of interest: FormContext and FieldContext. You can access the FormContext via the form's __MVC_FormValidation property, and one FieldContext per validated property via the FormContext's fields property.
So, to clear the validation errors, you can do something like this to a form:
var fieldContexts = form.__MVC_FormValidation.fields;
for(i = 0; i < fieldContexts.length; i++) {
var fieldContext = fieldContexts[i];
// Clears validation message
fieldContext.clearErrors();
}
// Clears validation summary
form.__MVC_FormValidation.clearErrors();
Then, you can hook that piece of code to whichever event you need.
Sources for this (quite undocumented) insight:
http://bradwilson.typepad.com/presentations/advanced-asp-net-mvc-2.pdf (Mentions FieldContext)
https://stackoverflow.com/a/3868490/525499 (For pointing out this link, which metions how to trigger client-side validation via javascript)
In order to complete clear the validation artifacts including the message, the coloured background of the input field, and the coloured outline around the input field, I needed to use the following code, where this was (in my case) a Bootstrap modal dialog containing an imbedded form.
$(this).each(function () {
$(this).find(".field-validation-error").empty();
$(this).find(".input-validation-error").removeClass("input-validation-error");
$(this).find(".state-error").removeClass("state-error");
$(this).find(".state-success").removeClass("state-success");
$(this).trigger('reset.unobtrusiveValidation');
});
Here you can use simply remove error message
$('.field-validation-valid span').html('')
OR
$('.field-validation-valid span').text('')
I've this issue for "Validation summery" after form ajax submit and done it like this:
$form.find('.validation-summary-errors ul').html('');
and complete code is:
$("#SubmitAjax").on('click', function (evt) {
evt.preventDefault();
var $form = $(this).closest('form');
if ($form.valid()) {
//Do ajax call . . .
//Clear validation summery
$form.find('.validation-summary-errors ul').html('');
}
});

hide div when click on form or focus on another control or press escape key

I am developing an web application. In this i provided a functionality means "autocomplete textbox". In this control, I need to show up 4 columns whenever user press keys in textbox, i need to collect these keys and send it to the service which will give us result as xml. then i convert xml to dataset and binded with datagird. for this i used jquery. after the result displayed ( i mean the result in datagrid which is placed in div), then i need to hide the div when the user clicks outside of the div or press escape key...
for this i used onblur event. but, when i click on the result then, i could not fire the click event for the div..
here is my jquery events...
function showList() {
if(document.getElementById("txt1").value.length > 3) {
$("#divList").hide("slow");
$("#divLoading").show();
$.ajax({
type : "POST",
url : "ajaxServerPage.aspx?streetname=" + document.getElementById("txt1").value,
success : function(responseText) {
$("#divLoading").hide();
$("#divList").show();
$('#divList').html(responseText);
//add button click events for buttons which are placed in table
$("#dataGridStreet .rowStyle").click(function(e) {
//Open_ModifyPopup($(this).attr("id"));
clickedRow($(this));
});
} // function(responseText)
});
}
}
How should I do this?
Thanks
Why reinvent the wheel: How about using a plugin to do it for you?

Resources