Enabling and disabling validation in cfform
Built-in validation in cfform is great, but sometimes, it is a little inflexible. What happens if we want to require a State field only if the Country field is US? There is no "built-in" way to specify such a thing. But there is a simple technique we can use. As always, use these tips only if you know what you are doing ;), as they may have side effects.
The key is to call the following when we want to disable the validation on a given field. We may want to call it when other field changes its value for example.
mx.validators.Validator.disable( this, "myFormName.myFieldName");
In order to enable it back, just call
mx.validators.Validator.enable( this, "myFormName.myFieldName");
Note that if the validation that you want to disable is “required”, you will not be able to get rid of the red star next to field.
The complete code:
<cfsavecontent variable="disableValidation">
mx.validators.Validator.disable( this, "myform.phone");
</cfsavecontent>
<cfsavecontent variable="enableValidation">
mx.validators.Validator.enable( this, "myform.phone");
</cfsavecontent>
<cfform name="myform" format="Flash">
<cfinput type="text" name="name" label="Name" required="true" message="Name is required" />
<cfinput type="text" name="phone" label="Phone" required="true" message="Phone is required" />
<cfinput type="button" value="Disable validation on phone" name="noVal" onClick="#disableValidation#" />
<cfinput type="button" value="Enable validation on phone" name="val" onClick="#enableValidation#" />
<cfinput type="submit" value="Submit" name="submit" />
</cfform>
Neil Bailey
Did you read my mind, my post on the MM forums, or are you just.....really, really smart :-D... I have been trying to figure out this very damn thing ALL WEEKEND!!! Thank you SO much..... I cannot even begin to imagine the rates you guys must get....... the stuff you come up with...
Holly Jones
William
Thanks so much for your help - you guys are life savers!
Neil Bailey
Mike
Chris Velevitch
Neil Bailey
if (!chk_first.selected && !chk_second.select && !_chk_third.selected) {alert("Some kind of user message");} else { formName.submitForm();}
in the onClick action of a button - label the button SUBMIT or whatever, but don't make it a type="submit".
But, again, I have been working with AS for like a week, so definitely check it out w/ someone who has a bit more experience.
Nahuel
First check if whether it is not compiling each time. You can check if the name of the swf generated is the same ( cached ) or it's always different ( it gets compiled each time ).
Simeon
That would be killer.
Simeon
To do what I asked just use the isValid function. It has the exact same syntax as the code in this example. More info can be found here.
http://livedocs.macromedia.com/flex/15/asdocs_en/mx/validators/Validator.html
Neil Bailey
Its generating a new SWF file every time; I know there's gotta be a setting I am missing... can you give me a firm push in the right direction?
Mike
-Mike
Laura
You can call
mx.validators.Validator.isStructureValid(this, 'myFormName')
to trigger validation on the entire form (only enabled fields will be validated)
That function will also return true if all the fields are valid or false otherwise.
Mike
You should blog that little gem.
-Mike
Mike
The icing on the cake would be to also get the listing of errors like CF by default.
<cfsavecontent variable="performValidation">
var validForm = mx.validators.Validator.isStructureValid(this, 'formName');
if (validForm == false){
//Show Alert
alert("There are errors in your form. Please go back and check the highlighted fields for errors.", "Errors Exist");
}
else if (validForm == true){
//action to perform when form is valid
}
</cfsavecontent>
-Mike
Laura
userOnError() (although it is one of those hacks that may change in the future)
<cfsavecontent variable="performValidation">
var validForm = mx.validators.Validator.isStructureValid(this, 'formName');
if (!validForm){
//Show Alert
userOnError();
}
else {
//action to perform when form is valid
}
</cfsavecontent>
Mike
Thanks again for the help. I actually found userOnError(); in the mxml soon after posting.
Pressing on,
-Mike
Nahuel
You have to avoid using cf logic inside your form or the savecontent or actionScript statements . For example you can not use cfif or any cf tag or variable that may change in each request. Actually the easiest thing is to use pure actionscript :)
Neil Bailey
Laura
yes, you must set it as:
theNameOfTheQuery.dataProvider = results;
the name of the query is the query that populates the repeater.
I will make an example of that when I get a minute.
Neil Bailey
At least tell me my questions are good ones that make you think for a second :) I appreciate your help more than you can imagine.
We have a dynamic set of panels that we're building w/ a repeater, and inside the panels, we need a series of checkboxes that are unique to each panel. These checkboxes are pulled from a database, and we cannot seem to come up with a way to do this w/ AS and as a result, our load time is ridiculous.
What we basically have now is:
<cfloop query=something>
<panel label="#name pulled from query">
<cfquery>
get new data based on original query
</cfquery>
<cfloop query=inner query>
<checkboxes built from inner query>
</cfloop>
</panel>
</cfloop>
can we do the above using only actionscript, and cut my load time, am I outta luck?
Casey A
First off, I'm really new to CF, I'm a VB guy so I can muddle my way through this!
Here's the issue, I would like to enable/disable certain form elements based upon specific cfselect options. I'm sure I need to use an onchange event to enable/disable the other cfselects, just not sure how to go about it...
Here's an example:
IF Q3=1 THEN Q4 AND Q4_COMMENTS enabled=yes, else q4 and q4_comments enabled=no value=""
<cfselect queryposition="below" label="Mid-Year Delivered Timely" name="q3" query="auditYN" value="respValue"
display="response" width="200">
<option>Please Respond</option>
</cfselect>
<cfselect queryposition="below" enabled="no" label="Please Explain" name="q4" query="auditReason"
value="reasonID" display="reason" width="200">
<option>Please Respond</option>
</cfselect>
<cftextarea type="text" enabled="no" name="q4_comment" width=200 height="50" label="Please Clarify">Please Clarify...</cftextarea>
Fernando Martel
if(!mx.validators.Validator.isStructureValid(this, "#arguments.form#"))
{
//CREATES POPUP WITH ERROR MSGS FROM INVALID FIELDS
var errors = CFFormValidators.getInValidFields();
var msg = "<ul>";
for(var key in errors)
msg += "<li>" + errors[key]["message"] + "</li>";
msg += "<ul>";
errorpopup = mx.managers.PopUpManager.createPopUp(this, FormErrorException, true, {message:msg});
errorpopup.centerPopUp(this);
}
else
{
submitForm();
}
Fernando Martel
for(var key in <yourform>)
mx.validators.Validator.enable(this,"<yourform>".key);
If only certain fields need to b enabled...i sometimes use a val_<fieldname> for all of those and then do something like this:
for(var key in <yourform>)
{
if(key.split("val_")[1] != undefined)
mx.validators.Validator.enable(this,"<yourform>".key);
}
or, since disables fields dont get validated, u cant try disabling the ones u dont want b4 validating..any questions just ask...
Fernando Martel
<cffunction name="validateSelect" hint="Fixes validation error for drop downs">
<cfargument name="form" type="string" required="yes">
<cfargument name="formE" type="string" required="yes">
<cfoutput>
<cfsavecontent variable="validateSelect">
if(#arguments.formE#.selectedIndex != 0)
mx.validators.Validator.disable(this,"#arguments.form#.#arguments.formE#");
else
mx.validators.Validator.enable(this,"#arguments.form#.#arguments.formE#");
</cfsavecontent>
</cfoutput>
<cfreturn validateSelect />
</cffunction>
nothing fancy....
Casey A
Casey A
This is a standard field, not a select.
brainDead
<mx:Model id="myModel">
<zipCode>{zipInput.text}</zipCode>
</mx:Model>
if (!mx.validators.Validator.isStructureValid(this, "myModel")) {
validator.validationError("modelInvalid", "There are invalid inputs to
the web service.", null);
}
Laura
I don't think it is possible. But what I do is to disable all fields and then enable some. I keep the list of group fields I want to maintain together and then I loop over a particular group's list to enable them.
Jeff
Jeff
Brook
Two Questions: Does anyone know how to add a custom validation type to the list of supported validation types? Is there a way to do it server side in the cfformvalidators.as?? I can't seem to get any changes made to that file to have any effect. Or is there a way to somehow use custom JS to do some validation and then add that field to the inValidFields array so that the field has the red outline and the error message on rollover?
Jut
If the fields are initially set to required="false", then the enable and disable functions don't seem to change the validation property. Can anyone else confirm this?
My goal is to create form fields that appear and disappear depending on previous choices. If they appear, I want the fields required. If they don't appear, they're not required.
TREX
for(var i = 0; i < mygrid.length; i++) {
var validForm = mx.validators.Validator.isStructureValid(this, 'formname');
if (!validForm){
//Show Alert
userOnError();
}
else {
//action to perform when form is valid
}
}
but that doesn't seem to work. Any advice would be appreciated. Thanks.
Matt
Can anyone help?
I need to be able to validate 4 tick boxes in a cfform.
The validation must work as follows:
At least 1 of the four tick boxes must be ticked.
If not then returns a message box stating at least 1 tick box must be ticked.
Any combination of the 4 tickboxes can be ticked.
I have been looking at javascript to do this but i really want to keep it in Flash, for consistancy.
Any ideas help would be appreciated.
Matt
BTW Just love this website, i have learnt soooooo much, keep it up guys.
Chris Velevitch
The easiest way to do this would be to initially make all tick boxes required and when one is ticked make all of them not required (via onClick) and if all of them get unticked make them all required (again by onClick).
Eugene
I have another problem. There is a required field in CFForm. When I hide this field (make it invisible), the asterisk is still there (visible). How can I hide it too? Any ideas?
Thanks.
Eugene
Neil
I'm certainly no expert, but I HAVE built my fair share of CF Flash form apps. The way that I would handle this would be to place the field in a form group (I would probably try a tile), and then instead of hiding the field, hide the entire tile.
You'll definitely need to play w/ the height and width attributes of the tile to make it so that it doesn't screw up the alignment of the rest of your form.
Hope this helps, sorry if its a waste of time :)
Scott
I am really new to this and some of what has been posted has totally confused me..but baby steps..baby steps...
I am struggeling with alligning labels by the : so it would all line up like thus:
First Name:
Email:
So I figured out how to do it with cfformitem. However when I make its corresponding text field required the asterisk goes all the way to the left of the label in the cfform item. Below is the code if you want to see it.
My question is: How do you make it so it will validate the required but not show and *
Laura
As fas as I know there is no way to get rid of the * if you set it as required
Mike Givens
this.fgpEquipDesc.required = true; // to turn the asterisk on
this.fgpEquipDesc.required = false; // to turn the asterisk off
<cfformgroup type="page" label="Equipment List" style="verticalGap:4">
<cfformgroup type="horizontal" label="Do you have Equipment?">
<cfinput type="radio" name="Equip" onClick="{(Equip.selectedData == 1)?toggleRequired(3):null}" label="Yes" value="1" required="Yes" message="You must answer the question - Do you have Do you have Equipment?">
<cfinput type="radio" name="Equip" onClick="{(Equip.selectedData == 0)?toggleRequired(3):null}" label="No" value="0" required="Yes" message="You must answer the question - Do you have Do you have Equipment?">
</cfformgroup>
<cfformgroup id="fgpEquipDesc" type="horizontal" label="Please List the Equipment :">
<cftextarea name="EquipDesc" width="300"></cftextarea>
</cfformgroup>
<cfinput type="Button" name="btn4" value="Continue" onclick="moveTab(4)">
</cfformgroup>
ActionScript code:
function toggleRequired(iTab) {
switch (iTab) {
// other case statements omitted for brevity
case 3:
if (Equip.selectedData==1) {
this.fgpEquipDesc.required = true;
} else {
this.fgpEquipDesc.required = false;
}
break;
}
}
A demo is at:
http://www.webcfmx.com/blogman/archives/entries/A7D04424-2B3C-7D38-AA60E9EA185C3FB5.shtml
binouch
mx.validators.Validator.disable(); is very usueful but it doesn't work for a form that is not format='flash' would any know an equivalent to format='html'. The reason why i want to do this is because i have a form with two submit buttons, one that submits the form and the other that would let the user save the entries that are already there.
Any one would have an idea on how to do that?
Thank you in advance.
Laura
No, that only works in flash forms. There are many ways of doing what you want, the easiest is to have the same action page, two submit buttons and then check in the action page which of the two was clicked to know what to do with the form data.
James McArdle
this.parent.indicator_mc.alpha= 0;
adios asterick ^.^
Kristin
Laura
You can't do it like that because required fields work differently. "visible" is simply a property of a control, which can be simply set to true/false with ActionScript at runtime, like you are doing in your example. "required", however, it is not a simple property. It is set at compile time, using additional mxml tags (see Validator), so it cannot be just set true/false at run time using the required attribute (which is only used by the compiler to create the necessary mxml tags if required is true)
Kristin
Thanks for explaining. I suspected something like that, but I wanted it to be as easy as the visible property. :)
Thanks for having such an awesome site!
Ken
In some instances you may need to hide the form field and thus disable the validation and the *
If you try this code, it does this. But and interesting thing is if you uncomment out the second textarea, the * is always displayed. I have tried the this.parent.indicator_mc.alpha= 0; code and am unable to get it to work.
Any ideas ???
<cfform name="myform" format="flash" ACTION="">
<cfformitem type="script">
function showField(){
var textarea1 = textarea1;
var textarea1label = textarea1label;
textarea1.visible=true;
textarea1.height='100';
textarea1.width='100';
textarea1label.text='Text Area 1';
mx.validators.Validator.enable( this, "myform.textarea1");
}
function hideField(){
var textarea1 = textarea1;
var textarea1label = textarea1label;
textarea1.visible=false;
textarea1.height='0';
textarea1.width='0';
textarea1label.text='';
mx.validators.Validator.disable( this, "myform.textarea1");
}
</cfformitem>
<cfformgroup type="Panel" height="400" width="400">
<cfinput type="text" name="textarea1label" value="Text Area 1" visible="no" height="0" width="0">
<cftextarea name="textarea1" label="{textarea1label.text}" required="Yes" height="100" width="100">This is a textarea.</cftextarea>
<!---<cftextarea name="textarea2" height="20" width="100" required="yes" label="Text Area 2"></cftextarea>--->
<cfinput type="Button" name="btn_hide" value="Hide Field" onclick="hideField()">
<cfinput type="Button" name="btn_show" value="Show Field" onclick="showField()">
</cfformgroup>
</cfform>
Mike Givens
<cfform name="myform" format="flash" ACTION="">
<cfformitem type="script">
function showField(){
textarea2.height='20';
textarea2.width='100';
mx.validators.Validator.enable( this, "myform.textarea1");
fgpTA2.visible = true;
fgpTA2.required = true;
fgpTA1.required = true;
}
function hideField(){
textarea2.height='0';
textarea2.width='0';
mx.validators.Validator.disable( this, "myform.textarea1");
fgpTA2.visible = false;
fgpTA2.required = false;
fgpTA1.required = false;
}
</cfformitem>
<cfformgroup type="Panel" height="300" width="400">
<cfformgroup id="fgpTA1" type="horizontal" label="Text Area 1" visible="Yes" style="marginLeft:0">
<cftextarea name="textarea1" required="Yes" height="100" width="100">This is a textarea.</cftextarea>
</cfformgroup>
<cfformgroup id="fgpTA2" type="horizontal" label="Text Area 2" visible="No" style="marginLeft:0">
<cftextarea name="textarea2" height="20" width="100"></cftextarea>
</cfformgroup>
<cfinput id="btn_hide" type="Button" name="btn_hide"
value="{(fgpTA2.visible==true)?'Hide Field 2 / Remove Required on Both':'Show Field 2 / Make Both Required'}"
onclick="{(fgpTA2.visible==false)?showField():hideField()}">
</cfformgroup>
</cfform>
You can try it at:
http://webcfmx.no-ip.info/prototypes/myform.cfm
James McArdle
<cfform name="myForm" format="Flash" Action="" onload="init()">
<cfformitem type="script">
function init()
{
fieldname.parent.indicator_mc.alpha=0;
}
</cfformitem>
</cfform>
Email me if you have any problems I will try and help.
Ken
Yes, thanks for that. I knew about this, but this would then require code to actually do the form validation which I was trying to avoid. It seems to me that my example code should work. I just don't understand that when another field is include the * is left.
James,
I was trying this in the function to hide the field.
I coppied your code and included a field, still did nothing that I could see the * was still there.
Ken
James Mcardle
James McArdle
code ;p
<cfform name="testform" format="flash">
<cfformgroup type="panel" label="Astericks of Doom" width="300">
<cfinput type="text" required="yes" name="myText_txt" width="100">
<cfformgroup type="horizontal">
<cfinput type="button" name="test" value="Asterick off" onClick="myText_txt.parent.indicator_mc._alpha=0;">
<cfinput type="button" name="test2" value="Asterick on" onClick="myText_txt.parent.indicator_mc._alpha=100;">
</cfformgroup>
<cfformgroup type="horizontal">
<cfinput type="button" name="test1" value="Field off" onClick="myText_txt.visible=false;">
<cfinput type="button" name="test3" value="Field on" onClick="myText_txt.visible=true;">
</cfformgroup>
</cfformgroup>
</cfform>
Can't make it much simpler than that.
Ken
Ken
Jeff
Thanks for your time.
function validate(UpdateType, item1, item2, item3, item4, item5, item6, item7, item8){
for(var key in profile){
mx.validators.Validator.disable(this, _root.profile.key);
<!---alert(form.key);--->
}
if(UpdateType == 'Personal'){
if(!mx.validators.Validator.isStructureValid(this, 'profile')){
userOnError();
}else{
<!---Updateform--->
UpdateForm();
}
}
}
Kristin
Troy
OK...now the question. How come when I set an input to both required=true, and I add a mask, the field starts out with a red border on load? Also, if I set a validation and also a mask, as I am STILL TYPING the data, the border goes red as soon as it fills in the first literal in the mask.
Any ideas how to work around these issues, or are they just the way it is? If so, I would call that a large defect in the great UI and Human Factors tools that using Flash should be offering us CF developers.
Thanks in advance!
Troy
Kevin
This is great, but how would you disable parts of the form when a tab of the tabnavigator is selected?
Mike Givens
<cfformgroup id="fgpEquipDesc" type="horizontal" label="Please List the Equipment :">
<cftextarea name="EquipDesc" width="300"></cftextarea>
</cfformgroup>
Then you'll be able to use ActionScript to toggle the section, fgpEquipDesc.enabled = false, based on your business logic; toggle, fgpEquipDesc.enabled = true, when the rules are met.
Here's an example: http://webcfmx.no-ip.info/prototypes/CFFlashExample2.cfm
Work your way through the tabs and on the last one, Safety/Training, if you answer 'Yes' to the first question, a second question will be enabled. You'll also note that the tabs are 'inactive' until you complete each section.
Einemillioneurohomepage für Onlineshops
It´s a very interesting Blog and simple answer of many questions.
Keep up the good work!
Dan Fredericks
I am using cfform type=flash. I am using the required = yes and message = blah blah blah.
When the error message displays, i only see 4 letters of my message, not the whole message. Is there a reason why my message box displays only a few text characters, and can I fix this problem?
thanks
Dan Fredericks
<cfformitem type="hrule" width="75%" />
when i removed this code from my page, the message error displayed properly. Why would this code mess with required="yes"?
thanks
Duane Hardy
<cfsavecontent variable="verify">
if(password.text != confirm_password.text) {
mx.controls.Alert.show('Password and Confirmation Password do not match!','Error');
return false;
}
return true;
</cfsavecontent>
Duane Hardy
<cfsavecontent variable="verify">
if(password.text != confirm_password.text) {
mx.controls.Alert.show('Password and Confirmation Password do not match!','Error');
return false;
}
return true;
</cfsavecontent>
James
James
JS Function to place in head
<script language="javascript1.2">
function checkcc() {
if ( document.form1.usecc[1].checked == true )
{
return (true);
}
}
</script>
<cfinput type="text" name="ccnumber" message="Please enter valid credit card number" onvalidate="checkcc" size="20" />
Gail