<asp:LinkButton ID="lbnImages" runat="server" CssClass="link"
PostBackUrl="AddImage.aspx" CausesValidation="True"
ValidationGroup="Save">Images</asp:LinkButton>
<asp:CustomValidator ID="cstval" runat="server" ControlToValidate="txtName"
ValidationGroup="Save" ErrorMessage ="Duplicate name"
OnServerValidate="Project_validation" />
I am checking for duplicates using the custom validator (server side code)
If the server side custom validator shows error the link button must not redirect to the page.
I need to stop the post back when the validator fires.
If you want to prevent the postback, you should do the validation client side by adding a custom javascript validation function to your validator control. This is described in this blog post.
If your validation logic can only run on the server, you will have to let the postback happen, but wrap all the code that you want not to run in e.g. an
if (Page.IsValid) { ... }
I see you are checking for duplicates, the only way to validate it without causing a postback is to make an ajax call.
Make a call to some service that will check if it's a duplicate or not, then if it's not valid stop it. Using jQuery syntax:
$("save_button").click(function(e){
$.ajax({
async: false, // will finish this request before executing anything else
url: "validation_page",
type: "POST",
data: ({name: "value from a field"}),
success: function(msg){
if (msg != "ERROR") // whatever msg is not valid
e.preventDefault(); // will not do the postback
}
})
});
Related
Need to know how handle ontextchanged /onChange events of HTML elements in DJANGO.
Like in ASP.NET we would simply call a server side function which needs to be executed whea an event is triggered.
for e.g
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"
ontextchanged="TextBox1_TextChanged**"></asp:TextBox>
Is there a similar way in DJANGO to hadle these events?
No, there is no equivalent in Django framework. You have to write your own Javascript code to detect changes and then send an AJAX request. It can be easily handled with jQuery library.
E.g :
$('#TextBox1').change(function() {
alert('input value changed : ' + $(this).val());
$.ajax({
url: "yourserver.com/path/", // endpoint
type : "POST", // HTTP method
data: $(this).val() // data sent
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="TextBox1" type="text" value="stack overflow" />
Read .change() and Jquery.ajax() documentation for more information
I have some code where I need two separate required field validators for one control, both in separate validation groups which are then validated by two separate buttons.
This approach works well when the buttons are clicked but both validators show if I enter a value in the textbox and then remove it.
Is there a way to turn this"lost focus" validation off? I only need it to validate when the buttons are clicked.
EDIT
Unfortunately, if I set EnableClientScript=false then I dont have any client notifications. What I want is for the dynamic error message to show (effectivly in the OnClientClick event of the button) but not the "lost focus" of the textbox.
Is there some way I can disable or "unhook" the lostfocus client event?
EDIT
A combination dDejan's answer and womp's answeer here sorted the problem perfectly.
My final code looks like this (for anyone else with a similar situation)...
Javascript...
<script type="text/javascript">
$(document).ready(function() {
$('body').fadeIn(500);
//Turn off all validation = its switched on dynamically
$.each(Page_Validators, function(index, validator) {
ValidatorEnable(validator, false);
});
});
function ToggleValidators(GroupName) {
$.each(Page_Validators, function(index, validator) {
if (validator.validationGroup == GroupName) {
ValidatorEnable(validator, true);
} else {
ValidatorEnable(validator, false);
}
});
}
</script>
ASPX Control Example...
<telerik:RadTextBox Width="196px" ID="txtFirstName" runat="server" MaxLength="50" Skin="Black"></telerik:RadTextBox>
<asp:RequiredFieldValidator ID="valFirstName" CssClass="Validator" runat="server" EnableClientScript="true" Display="Dynamic" ErrorMessage="You must enter your first name." ControlToValidate="txtFirstName" ValidationGroup="NeededForEmail"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" CssClass="Validator" runat="server" EnableClientScript="true" Display="Dynamic" ErrorMessage="You must enter your first name." ControlToValidate="txtFirstName" ValidationGroup="NeededForSubmit"></asp:RequiredFieldValidator>
ASPX Button Code...
<asp:Button ID="btnGetConfCode" runat="server" Text="Get Confirmation Code" OnClientClick="ToggleValidators('NeededForEmail')" OnClick="btnGetConfCode_Click" Width="100%" ValidationGroup="NeededForEmail"/>
<asp:Button ID="btnRegisterUser" runat="server" Text="Register" OnClientClick="ToggleValidators('NeededForSubmit')" OnClick="btnRegisterUser_Click" Width="100px" ValidationGroup="NeededForSubmit" />
So, now there is no validation until a user clicks either the "Get Email Confirmation Code" button or the "Register" button.
If they click the "Get Email Confirmation Code" button all of the controls validate apart from the textbox where the user is to input the email validation code and we only see one validator message.
If they click the "Register" Button then all of the controls validate and we only see one validation message.
If either button is pressed, the user goes back, adds and then removes some text then we only see one validator. Before this change you used to see both messages saying the same thing.
Thank you for help guys
You can set if the validators are "active" or not with client side code using the ValidatorEnable function. Basically it goes like this
var validator = document.getElementById('<%=Validator1.ClientID%>');
ValidatorEnable(validator , state); //where state is boolean
You can also trigger the validator to validate on some event (like for example the click of the buttons) using the ValidatorValidate(validator) function.
I am not sure which would work better for you (enabling/disabling the validators or custom triggering of the validation) but I suggest this article that will guide you in the right direction
ASP.NET Validation in Depth
There's no way to unhook them if EnableClientScript=true.
What you could do is set it to false. Then create a javascript validation method that is called on your submit-button onClientClick event.
In your method, you would have to call ValidatorValidate(control) for each control you want to validate client side
There's an example here:
http://msdn.microsoft.com/en-us/library/Aa479045#aspplusvalid_clientside
You could turn off the javascript validation by setting EnableClientScript="false" that would get rid of the lost focus validation.
You can use Custom Validator controls instead and either validate the input using Javascript on the client or within the event handler on the server. Ensure you set ValidateEmptyText="true" on the validation controls otherwise the events will not fire on an empty field.
Try to Enable on Both button click using javascript and disable it on textbox blur event.
Try resetting the onchange event for the input-control.
$(document).ready(function () {
$("#controlid").each(function () { this.onchange = null; })
});
var validator = document.getElementById('<%=Validator1.ClientID%>');
ValidatorEnable(validator , state);
It is working in javascript but when we use the page.Isvalid function on Server side it creates the problem to check page is valid or not.
simply type this code in page_load event
textboxname.Attributes.Add("onblur","ValidatorOnChange(event);");
i am using validators for validation and on linkbutton i am diaplaying popup.
my problem is i want to disable linkbutton means until page is validated means the popup should not be displayed till the page gets validated
<asp:LinkButton ID="LinkButton1" runat="server" CssClass="addProduct-disable" Enabled ="false"
Text="Assign Filter Criteria" CausesValidation="true"></asp:LinkButton>
Try to validate client-side, if possible, via AJAX-Methods.
You may consider using the jQuery event.preventDefault() method.
$('[id$="LinkButton1"]').click(function(event) {
if(! valdiateYourPage() ) {
event.preventDefault();
// display validation errors or something
}
else {
//proceed as normal
}
});
Put your page validation logic in the valdiateYourPage() javascript method. If it valdiates, then process as normal, if not then preventDefault() will stop any further event execution by your LinkButton.
I need to run some script by onclick() of some , checkbox particularly, to decide should i invoke WebForm_doPostBack() or not.
If I will submit form in myScript() myself, it will not cause validation of another asp.net validators, so I really need a native WebForm_doPostBack() call.
Should I handle a submit form event or are there any more "asp.net" ways to do it?
CustomValidators don't work with checkboxes:).
Just to ensure your assumptions that custom validators do not work with checkboxes is not the ONLY reason for wanting to handle the checkbox click seperately, here is some code that will validate checkboxes using ASP.NET custom validators.
Custom Validators have a ClientValidationFunction property that is called automatically when the __doPostback is called or the form is submitted.
//The Script
function validateCheckBox(source, arguments)
{
if(!source.checked) arguments.IsValid = false;//set IsValid property to false
}
//The Validator
<asp:CustomValidator ID="validateCheckbox" runat="server" ControlToValidate="CheckBox1" ErrorMessage="You REALLY need to check this!" Display="Static" ClientValidationFunction="validateCheckBox"/>
Don't you try simply putting your own validation at submit button like that :
btnSubmit.Attributes["onclick"] += "return myValidation();";
<script>
function myValidation()
{
// if you do not want to postback just return false...
return true;
}
</script>
EDIT : You can use Page_ValidationActive to programmatically enable / disable the client side validation of your page.
Page_ValidationActive A Boolean
value that indicates whether
validation should take place. Set this
variable to false to turn off
client-side validation
programmatically.
I've got this textBox which triggers off an ajax request using jQuery:
<asp:TextBox ID="postcodeTextBox" runat="server" Text='<%# Bind("POSTAL_ZIP_CODE") %>'>
$(document).ready(PageLoad);
function PageLoad() {
$(container + 'parentProjectTextBox').change(GetProjectName);
}
function GetProjectName() {
var projectNumber = $(this).val();
if (projectNumber == '') return;
$(container + 'parentProjectPanel').block({ message: '<img src="../Resources/RadControls/Ajax/Skins/Default/loading7.gif" />' });
$.ajax({
type: 'POST',
url: projectMasterWebServicesUrl + 'GetProjectName',
data: "{'projectNumber':'" + projectNumber + "'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: GetProjectNameOnSuccess,
error: GetProjectNameOnError
});
}
This ajax request gets a list to populate this dropdown:
<asp:DropDownList ID="cityDropDownList" runat="server" OnDataBound="cityDropDownList_DataBound">
<asp:ListItem Text="...Select..." Value="0">
</asp:ListItem>
</asp:DropDownList>
Everything works fine. The only problem I'm having is that when I update my formView priod to saving that record I can't see the value that was set to that dropdown. As I'm populating this dropdown in the client side I supose ASP.NET loses track of that ....
Does anyone have any insights?
Apparently when I switch on/off the EnableEventValidation property for that page I sometimes get the correct value.....
Thanks !
You should create a hidden field store that value. Update that HiddenField in your Javascript and then read it on the server side. Also, if you have EventValidation=true and you change the items in the dropdown list you will get well known exceptions.
This may not be the problem...but are you checking for Page.IsPostBack in your Page_Load?
I've made that mistake way too many times.
If you are loading that drop down control from the Page_Load, and you are not checking
if (!Page.IsPostback)
you will reload the control. Then when you get the value from the drop down...the value is gone because you reloaded the dropdown.