Recommendations for implementing a validation class?

I am implementing a validation class in classic ASP. How should the validation class interface work with my other classes?

My current setup: Methods of a set of user classes call the corresponding validation method in the validation class. Any errors that occur are stored in User.mError. For example, here's my set method for an email item variable in ASP Classic:

Class User
  Property Let Email(EmailInput)
     If (myValidation.isEmail(EmailInput)) then
        mEmail = EmailInput
     Else
        mError = "Invalid Email Address format."
     End If

      

I don't like how I need an error member variable for every object that my validation class calls. Suggestions for a better setup?

Any suggestions for a validation architecture that I should consider as a reference?

0


source to share


4 answers


You should try the validation concept used in ajaxed (which is an AJAX library for classic ASP - www.webdevbros.net/ajaxed/ ). Unfortunately the validator will be officially released in version 2.0, but it's already available in SVN - you can easily use it without the whole library (standalone)

Ajaxed has a class called validator that you can use to validate your business objects. This requires the creation of an isValid () method that takes a Validator as an argument and returns if the instance is valid or not. The isValid () method is called before the instance is saved. It does all the checks and populates the given validator if anything is invalid.

Example:



class User
    public firstname
    public lastname

    'validates the user instance
    '- call before save()
    public function isValid(byRef v)
        isValid = true
        if len(firstname) < 5 then
            v.add "firstname", "Firstname must be at least 5 chars long."
            isValid = false
        end if
        if len(lastname) < 5 then
            v.add "lastname", "Lastname must be at least 5 chars long."
            isValid = false
        end if
    end function

    public sub save()
        'do some DB stuff
    end sub
end class

'usage scenario 1 (simple - we just know if valid or not)
set u = new User
if u.isValid(new Validator) then
    u.save()
else
    response.write("User is invalid. some error happend")
end if

'usage scenario 2 (detailed - we have an error summary)
set u = new User
u.firstname = "Michal"
set v = new Validator
if u.isValid(v) then
    u.save()
else
    'the validator offers a helper to create a validation summary
    response.write(v.getErrorSummary("<div><ul>", "<ul/></div>", "<li>", "</li>"))
end if

'usage scenario 3 (we can even validator more users in one go)
set u1 = new User
set u2 = new User
set v = new Validator
u1.isValid(v)
u2.isValid(v)

if v then
    u1.save()
    u2.save()
else
    response.write("something is invalid")
end if

      

I have been using this apruach for many years and is very flexible. The Validator class can be used as a standalone class, but I would recommend that you use the ajaxed library in general. This allows you to simplify ASP development.

+2


source


I would suggest looking at the Validator related classes provided by the .net framework.

In your case, you can have a Validator class (specific to EmailValidator) which can have a method named Validate that takes a string, returns a boolean

You can also pass ErrorMessage as one of the parameters to the Validate function for example




Psuedo Code.

class EmailValidator
...
function Validate(byval EmailAddress as string, optional byval Result as string) as boolean)
..
if (condition success)
result = success
elseif (emailafddress doesnt have @)
result = "invalid email address. missing @"
endif
end function
end class

      

You may receive an error message if you want to control it.

I suggest to colleagues from SO to suggest any drawbacks on this.

0


source


Spring has its own validator pattern to validate complex objects and return multiple errors. He describes in detail here .

0


source


I wrote my own Validator class in several ways. Validation in nature does not necessarily require an instance of an object, so I created a class with static methods for validation. I used one validator method where you need to pass a type (e.g. E-mail, Name, website ...) or multiple methods for each type. In the end, there is only one algorithm I need, so I went with one method. Basically, there are class properties that contain your regular expressions for each type, as well as the corresponding error message for that type. These all fit into a class similar to the one below:

class Validation
{

    // define the properties for dealing with different type validations
    public static $firstNamePattern = '/[-a-zA-Z0-9._ ]{2,}/';
    public static $lastNamePattern = '/[-a-zA-Z0-9._ ]{2,}/';
    // ... more fields


    public static function validateText($type, $text, $fieldName)
    {
        $pattern = $type."Pattern";
        if ($this->$pattern != '')
        {
            // perfom the validation
            // ...
            return true; // or false
        }
    }

    // other validation methods below
    // ...

}

      

Then you can call this method from anywhere you need (for example, when validating form input).

if (Validation->validateText('firstName', $formFirstName, 'First Name'))
{
    // validation passed
}
else
{
    // validation failed
}

      

Sorry the above is written in PHP and the question was about ASP but you got my drift.

0


source







All Articles