Search code examples
asp-classicvbscriptlate-binding

How do you call a method from a variable in ASP Classic?


For example, how can I run me.test below?

myvar = 'test'
me.myvar

ASP looks for the method "myvar" and doesn't find it. In PHP I could simply say $me->$myvar but ASP's syntax doesn't distinguish between variables and methods. Suggestions?

Closely related to this, is there a method_exists function in ASP Classic?

Thanks in advance!

EDIT: I'm writing a validation class and would like to call a list of methods via a pipe delimited string.

So for example, to validate a name field, I'd call:

validate("required|min_length(3)|max_length(100)|alphanumeric")

I like the idea of having a single line that shows all the ways a given field is being validated. And each pipe delimited section of the string is the name of a method.

If you have suggestions for a better setup, I'm all ears!


Solution

  • You can achieve this in VBScript by using the GetRef function:-

    Function Test(val)
      Test = val & " has been tested"
    End Function
    
    Dim myvar : myvar = "Test"
    Dim x : Set x = GetRef(myvar)
    Response.Write x("Thing")
    

    Will send "Thing has been tested" to the client.

    So here is your validate requirement using GetRef:-

    validate("Hello World", "min_length(3)|max_length(10)|alphanumeric")
    
    
    Function required(val)
        required = val <> Empty
    End Function
    
    
    Function min_length(val, params)
        min_length = Len(val) >= CInt(params(0))
    End Function
    
    
    Function max_length(val, params)
        max_length = Len(val) <= CInt(params(0))
    End Function
    
    
    Function alphanumeric(val)
        Dim rgx : Set rgx = New RegExp
        rgx.Pattern = "^[A-Za-z0-9]+$"
        alphanumeric = rgx.Test(val)
    End Function
    
    
    Function validate(val, criterion)
    
        Dim arrCriterion : arrCriterion = Split(criterion, "|")
        Dim criteria
    
        validate = True
    
        For Each criteria in arrCriterion
    
            Dim paramListPos : paramListPos = InStr(criteria, "(")
    
            If paramListPos = 0 Then
                validate = GetRef(criteria)(val)
            Else
                Dim paramList
                paramList = Split(Mid(criteria, paramListPos + 1, Len(criteria) - paramListPos - 1), ",")
                criteria = Left(criteria, paramListPos - 1)
                validate = GetRef(criteria)(val, paramList)
            End If
            If Not validate Then Exit For
        Next
    
    End Function
    

    Having provided this I have to say though that if you are familiar with PHP then JScript would be a better choice on the server. In Javascript you can call a method like this:-

    function test(val) { return val + " has been tested"; )
    var myvar = "test"
    Response.Write(this[myvar]("Thing"))