I am using the AJAX Cascading drop down list but want to add event validation e.g. the compare validators.
As the cascading drop down list requires the page event validation to be disabled what is the best way to do the validation?
Thanks
Andy
Validation Attempt:
I have tried to use a custom validator which calls a Javascript function but it doesnt seem to be picking up the control. I get the following error Microsoft JScript runtime error: Object required
function ValidateCostCentCat(source, arguments)
{
var countryList = document.getElementById("ddlCategory");
if (null != countryList)
{
var iValue = countryList.options[countryList.selectedIndex].value;
if (iValue == "Select Category")
{
arguments.IsValid = true;
}
else
{
arguments.IsValid = false;
}
}
}
The mark-up for the custom validator is
<asp:CustomValidator ID="valcustCategory" runat="server" CssClass="error" Display="Dynamic" ValidationGroup="DirectHire" ClientValidationFunction="ValidateCostCentCat"
ErrorMessage="Please select a Cost Centre Category from the drop down list provided.">!</asp:CustomValidator>
Read This: http://www.w3schools.com/PHP/php_ajax_database.asp
The example demostrate how to select a
value from a dropdown box sent it via
AJAX and get back the responce!
in the middle you can do all the
Validation that you want!
UPDATED with code just for fun! ;-)
Assuming your select is
<asp:DropDownList ID="CategoryDropDownList" runat="server">
Then you function look like this:
function ValidateCostCentCat(source, arguments)
{
var countryList = document.getElementById("CategoryDropDownList");
if (null != countryList)
{
var iValue = countryList.options[countryList.selectedIndex].value;
if ( iValue == "Select Category" ) {
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
}
This must work as expected!
hope this help!
Related
I am currently involved in developing a system using asp.net(VB). I have applied required validator so that to obtain correct inputs from user. But now I am having some issues. I also must allow the user to leave the text boxes empty too. Then can submit the page. so consider the form can validate true if thetext box are left empty or with values.
how to solve this issue frends? Kindly help me. Thank You very much
When you use a required Validator, the text will be required. Hence the name...
If you want more complex validation you need to use a CustomValidator
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1" runat="server" ErrorMessage="Text not long enough" ValidationGroup="myGroup" ClientValidationFunction="myCustomValidation"></asp:CustomValidator>
<script type="text/javascript">
function myCustomValidation(oSrc, args) {
var textboxValue = args.Value;
if (textboxValue == "") {
args.IsValid = true;
} else {
if (textboxValue.length > 4) {
args.IsValid = true;
} else {
args.IsValid = false;
}
}
}
</script>
We have a form used by a number of our customers where someone can register on their web site. It's customizable in that the owner of the form can set a field to be shown or hidden on the form and also required. However, some fields if shown, require that another field be set for the form to be valid. So the validation can be tricky. The other tricky part is that we wanted all the error messages to show together in the validation summary. If I simply had my own function that was called onclientclick for the linkbutton I couldn't add any error messages it generated to the validation summary.
So the solution that we found originally was creating a custom validator on the page without setting it's controltovalidate property but leaving it's clientvalidationfunction set to the function we wanted to call. This allowed us to set the errormessage of the sender argument so that it then showed up in the validationsummary.
We needed to add some additional validation logic and when doing this I realized that the page no longer works as it used to (I think it was working back in .net 2, now we're on .net 4).
Here's the basic html code I have.
Web page -
<asp:ValidationSummary ID="vsummary" runat="server" HeaderText="Oops, it appears the following required fields are not completed." CssClass="error" />
<asp:CustomValidator ID="cstCustomScripts" runat="server" ClientValidationFunction="ValidateExtraFields" />
...additional form fields here
<asp:LinkButton ID="btnAddUpdate" runat="server" onclick="SubmitProfile" />
And the javascript that gets called by the custom validator...
function ValidateExtraFields(sender, args) {
args.IsValid = true;
if (typeof window.RelocationSelectionRequired == 'function') {
if (!RelocationSelectionRequired()){
args.IsValid = false;
sender.errormessage = "If you are open to relocating, please select the state(s) and cities.";
return;
}
}
if (typeof window.ValidateHomeState == 'function') {
if (!ValidateHomeState()) {
args.IsValid = false;
sender.errormessage = "Home state is required.";
return;
}
}
if (typeof window.ValidateWorkState == 'function') {
if (!ValidateWorkState()) {
args.IsValid = false;
sender.errormessage = "Work state is required.";
return;
}
}
var invalidNumberField = "";
$("[data-validate-function='GreaterThanZero']").each(function () {
var t = $(this);
if (t.val().trim() == "0") {
args.IsValid = false;
invalidNumberField = t.attr("controlName");
return false;
}
});
if (invalidNumberField.length > 0) {
sender.errormessage = invalidNumberField + " cannot be zero.";
return;
}
}
In the past the function would successfully append any messages from this function to the validationsummary control and not submit the form. Now it still appends the message but the form also submits when it shouldn't. Does anyone know if this is a result of moving from .net 2 to .net 4? Or is there some other reason it no longer works? Thanks.
Your link button should have CauseValidation = true for the validation to be fired.
You said that you beleive this worked in .net 2.0. I found a page about Breaking changes in ASP.NET 4. I don't see anything specific about the CustomValidator Control that would be a breaking change. But it speaks of a setting in web.config that you can use try. It will lower the Rendering Compatability Version to 2.0 or 3.5.
<pages controlRenderingCompatibilityVersion="2.0" />
or
<pages controlRenderingCompatibilityVersion="3.5" />
If that don't work you can also try to lower the .net version of the web project to 2.0 or 3.5.
I need to have a custom validation for a "Save" operation in my page. The requirement is that, I need to display the alert and when I click the OK button in the alert, my page should not be posted back.
Here goes my code.
function RedirectForSaveValidation(source,arguments) {
var StatusFlag = '';
StatusFlag = document.getElementById('<%= HiddenStatusFlag.ClientID%>');
if (StatusFlag == "F") {
alert("Selected student entry has been qualified for lead. Entry cannot be modified...!");
arguments.IsValid = false;
}
if (StatusFlag == "Q") {
alert("Selected student has been scheduled for interview/counselling. Entry cannot be modified...!");
arguments.IsValid = false;
}
if (StatusFlag == "S") {
alert("Selected student entry has been scheduled with interview/counselling. Entry cannot be modified...!");
arguments.IsValid = false;
}
if (StatusFlag == "I") {
alert("Selected student entry has been converted to Intake. Entry cannot be modified...!");
arguments.IsValid = false;
}
window.location.assign("EnquiryRegister.aspx");
}
I call this function in my button click.
<asp:Button ID="btnSaveEnquiryRegister" runat="server" Text="Save Enquiry Register" CssClass="button" OnClick="btnSaveEnquiryRegister_Click" ValidationGroup="valEnquiry" OnClientClick="RedirectForSaveValidation();"/>
The issue is, I am not getting any alert as I have specified and my page is posted back. What am I missing?
The correct way for solving this problem would be to use CustomValidator control and its ClientValidationFunction property. With this you can integrate your client side validation with ASP.NET validation functionality.
Have a look at the example on MSDN documentation.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.clientvalidationfunction.aspx
Hope it helps!
Regards,
Uroš
Your are using a Custom Validation function directly on button click. Look you are passing two parameters in the Function and OnClientClick you are not passing parameters. this method should be called through CustomValidator control of asp.net.
Or just remove parameters from method. Use method without parameters
well this is not the correct way to implement the custom validator look at this http://www.w3schools.com/aspnet/control_customvalidator.asp and http://www.w3schools.com/aspnet/showaspx.asp?filename=demo_customvalidator (show you how to do it properly)
but still if you want to do the validation like this you have to return false in case it is not valid
so your validation function should return true (in case it is valid) or false
then
<asp:Button ID="btnSaveEnquiryRegister" runat="server" Text="Save Enquiry Register" CssClass="button" OnClick="btnSaveEnquiryRegister_Click" ValidationGroup="valEnquiry" OnClientClick="return RedirectForSaveValidation();"/>
Silly me! The issue was with getting the value of my hidden field.
var StatusFlag = '';
StatusFlag = document.getElementById('<%= HiddenStatusFlag.ClientID%>').value;
I had missed to include value property so the variable had empty value which caused the validator to fail.
I have an ASP.NET TextBox with a CustomValidation control that invokes client side validation script.
<asp:TextBox ID="txtSubsContrRbtAmt" runat="server"
CssClass="textEntry NumericInput" Width="150px"
Text="" onKeyUp="SumValues();" MaxLength="16"></asp:TextBox>
<asp:CustomValidator ID="cvalSubsContrRbtAmt" runat="server" ClientValidationFunction="ValidatetxtSubsContrRbtAmt"
ControlToValidate="txtSubsContrRbtAmt" CssClass="errlable" ErrorMessage="Max Decimals = 7"
SetFocusOnError="True" ValidationGroup="CarbsAdd"></asp:CustomValidator>
Here's the Client script:
function ValidatetxtSubsContrRbtAmt(source, args) {
var txtSubsContrRbtAmt = document.getElementById("<%=txtSubsContrRbtAmt.ClientID%>");
var amount = txtSubsContrRbtAmt.value;
args.IsValid = ValidAmount(amount);
if (!args.IsValid)
txtSubsContrRbtAmt.focus();
}
function ValidAmount(amount) {
if (isNumber(amount)) {
return (RoundToXDecimalPlaces(amount, 7) == amount);
}
else {
return true;
}
In the ValidatetxtSubsContrRbtAmt function, the "source" parameter is the CustomValidator. That control has a property "ControlToValidate." If I can get to it, I can programmatically retrieve the value from that control and not have to have a separate function to validate each textbox.
jQuery is too much for me at this point, I'm looking for a plain old Javascript approach, please.
You don't have to get the text box. You can get the value from args.Value. The focus should be set automatically if you set SetFocusOnError="true".
function ValidatetxtSubsContrRbtAmt(source, args) {
var amount = args.Value;
args.IsValid = ValidAmount(amount);
}
You should be able to get to the control from the source object.
function ValidatetxtSubsContrRbtAmt(source, args) {
var controlToFocusOn = source.ControlToValidate;
you can switch that out with "document.getElementByID()" to get the ID or whatever attribute you need
var controlId = document.getElementById(source.ControlToValidate).id;
}
now you can focus or do what you need with the control. I had to access the the actual ControlToValidate earlier today from a CustomValidator.
I want to run whatever client-side validation routine is hooked up to a particular text input element.
The validation has been set up using CustomValidator:
<asp:textbox id="AddEstTime" runat="server" Width="55px"></asp:textbox><br />
<asp:CustomValidator ID="AddEstTimeCustomValidator" ClientValidationFunction="AddEstTimeCustomValidator_ClientValidate" OnServerValidate="AddEstTimeCustomValidator_ServerValidate" ErrorMessage="Please enter a time" ControlToValidate="AddEstTime" runat="server" Display="Dynamic" ValidateEmptyText="true"/>
<asp:CheckBox ID="AddIsTM" runat="server" Text="T&M" />
and the javascript:
function AddEstTimeCustomValidator_ClientValidate(sender, args) {
var checkbox = $("input[id$='IsTM']");
args.IsValid = checkbox.is(":checked") || args.Value.match(/^\d+$/);
}
When the CheckBox "AddIsTM" state changes, I want to revalidate the textbox "AddEstTime", using its hooked-up CustomValidator "AddEstTimeCustomValidator".
I am aware of focus -> add a character refocus -> remove character. I am trying to find a more correct way. New to asp.NET.
After looking through the Microsoft client-side code, I came up with this which seems to work:
// client-side validation of one user-control.
// pass in jquery object with the validation control
function ValidateOneElement(passedValidator) {
if (typeof (Page_Validators) == "undefined") {
return;
}
$.each(Page_Validators, function (index, value) {
if ($(value).attr("id") == passedValidator.attr("id")) {
ValidatorValidate(value, null, null);
}
});
}
This was after examining the Page_ClientValidate function:
function Page_ClientValidate(validationGroup) {
Page_InvalidControlToBeFocused = null;
if (typeof(Page_Validators) == "undefined") {
return true;
}
var i;
for (i = 0; i < Page_Validators.length; i++) {
ValidatorValidate(Page_Validators[i], validationGroup, null);
}
ValidatorUpdateIsValid();
ValidationSummaryOnSubmit(validationGroup);
Page_BlockSubmit = !Page_IsValid;
return Page_IsValid;
}
thx sennett (voted)
i just ran the simplest JS
Page_ClientValidate();
if you have a validation group then is
Page_ClientValidate("validationGroupName")
If you want stick with ASP.NET validators eventually you can abuse Validation Groups, but I think that this approach will give you nothing but trouble. Other option is to use jQuery on the client (nice list) only then you will have to duplicate validation on the server side, or to avoid that call server methods from client validations.