Now here is an interesting problem :)
I am trying to do validation of a text field which is required to have a value; i.e. like the RequiredFieldValidator is doing, but... The problem is that I only want the validation if the field is visble. A small sample of reason is included here (extract from asp.net generated page)...
Code:
<html>
<head>
<script type="text/javascript" language="javascript">
function toggleVisibility(id1)
{
var o1 = document.getElementById(id1);
o1.style.display =
((o1.style.display != "none")? "none" : "");
}
</script>
</head>
<body>
<table cellspacing="6" cellpadding="0" border="0">
<tr>
<td align="Right" valign="Top"><span class="inputLabel">include link</span></td>
<td valign="Top"><input id="ocms_pageLink" type="checkbox" name="ocms:pageLink"
onclick="toggleVisibility('ocms_pageTitleLinkComponent');" /></td><td valign="Top"></td>
</tr>
<tr id="ocms_pageTitleLinkComponent" style="display:none;">
<td align="Right" valign="Top"><span class="inputLabel">*link title</span></td>
<td valign="Top" colspan="2"><input name="ocms:pageTitleLink" type="text" id="ocms_pageTitleLink" /></td>
</tr>
</table>
</body>
</html>
That is, the visibility of some fields are toggled using a script and I only want the validation to occur while visible. So I cannot use a RequiredFieldValidator since it will validate dispite the visibility. Therefore, I set out to create my own CustomValidator (using client-side scripting). After quite some debugging I final got the client-side script to fire... sometimes!
The client-side script I made asked about the display style property of the element, and if set to
block I would validate the field. The problem seems to be that the script is only firing when there is in fact a value in the field. The reason for this is to be found in
WebUIValidation.js, which is part of the ASP.NET framework.
The problematic function is this one...
Code:
function CustomValidatorEvaluateIsValid(val) {
var value = "";
if (typeof(val.controltovalidate) == "string")
{
value = ValidatorGetValue(val.controltovalidate);
if (ValidatorTrim(value).length == 0)
return true;
}
var args = { Value:value, IsValid:true };
if (typeof(val.clientvalidationfunction) == "string") {
eval(val.clientvalidationfunction + "(val, args) ;");
}
return args.IsValid;
}
So, if the length of the value of the field is 0 then the validation passes! Therefore, I could solve the problem by changing the function, but it is not a possible solution since I would have to do this on all the machines on which the system is deployed. So there must be another solution.
I have tried to apply a RequiredFieldValidator to the control, and then add dummy text to the field when not visible and the remove it when visible, but wasn't able to make it work.
Summary: I want to do a required field validation on a text field but only when it is visible (
display:block).
Does anyone have the same problem? Do you have a solution? I am interesed in this solution.
Thanks a lot, Jacob.