Required Field conditional on button pressed - asp.net

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

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

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.

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

Range validation

Suppose I have a table like:
create table
{
id numeric(5,3),
code varchar(10)
}
I have two text boxes in my form for the two fields.
Suppose if I type 1234578 in the first text box the error has been thrown in ASP.NET because I crossed the limit.
How can I validate in JavaScript or some other way for that particular range validation?
Let's take one textbox only. Attach an 'onchange' event handler to your textbox like this:
<input type="text" onchange="handleChange(this);" />
Then declare a script for validation like this:
<script>
function handleChange(input) {
if (input.value > ..your_value_here..) alert ("Invalid input");
}
</script>
Please note that the alert pop-up used here should not be actually used. Use a more subtle reminder at a more appropriate moment. The alert here is only to make things simple.

Resources