简体   繁体   中英

Incrementing values in form field names

I need to validate X number of fields. Each field is named "testFieldX", where X is any real number greater that 1.

So basically what I have in a form are fields with names:

testField1
testField2
testField3

etc.

I need to iterate over all of them and validate.

Let's assume I have 5 fields.

Then

<cfloop index="i" from="1" to="5">
    <cfif form.testField & i EQ "">
        Show error
    </cfif>
</cfloop>

However it does not work. I get an error that the field name "testField" does not exists, which is true (only testField1+) exist. It seems like the things are not concatenating. Does it work only with strings?

How can I solve this problem?

The syntax you're after is:

<cfif form["testfield" & i] EQ "">

That will concatenate the strings as you're expecting.

<cfif structKeyExists(form,"test1")>
    <cfloop from="1" to="3" index="i">
        <cfif form["test" & i] eq ''>
            Error : <cfoutput>#i#</cfoutput><br />
        </cfif>
    </cfloop>
</cfif>

<form name="sub" method="post">
    Test1: <input type="text" name="test1" id="test1" /><br />
    Test2: <input type="text" name="test2" id="test2" /><br />
    Test3: <input type="text" name="test3" id="test3" /><br />
    <input type="submit" value="Submit" />
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM