Skip to content

Using the Library: Server Side Validations

Kevin Cheng edited this page Jul 16, 2017 · 1 revision

First, let's check the server-side validations. Best practice is to validate on the server no matter how well our client-side validations are written, as client-side validations is dependent on so many variables. To validate the inputs, we call the function ScissorValidations.Validator.Validate(), which accepts an instance of the Employee class (can be a new or existing instance) and the mapping definition Dictionary<String, Validator.FieldMap>.

protected void submitButton_Click(object sender, EventArgs e)
{
    errorsList.DataSource = null;
    errorsList.DataBind();

    var p = new Employee();

    var fieldMappings = new Dictionary<String, String>
    {
        {"FirstName", firstNameInput.Text},
        {"MiddleName", middleNameInput.Text},
        {"LastName", lastNameInput.Text},
        {"Email", emailInput.Text},
        {"DateEmployed", employmentDateInput.Text},
        {"YearsExperience", yearsExperienceInput.Text},
        {"Rating", ratingInput.Text}
    };

    var validation = ScissorValidations.Validator.Validate(p, fieldMappings);

    if (validation.Failed)
    {
        errorsList.DataSource = validation.Findings;
        errorsList.DataBind();
    }
}

The fieldMapping variable defines how the class properties map to the page controls. Each element in the map holds the name of the property, and the value to be validated. The Validate() function returns all validation results found, which can be used as a data source for a repeater control, for example. If none are returned, then it means that the inputs passed validation based on the defined rules, and can now be safely saved.

Below is how the validation results appear in the Repeater control.

Getting Validated Data

As a shortcut, it is also possible to let the Validate() function auto-assign the validated values directly into the data class instance that was passed. This is to minimize the need to assign and perform any casting needed which were already done internally during the validation process. Note that this only passes any values deemed valid by the validation process. To enable this functionality, set the global setting ScissorValidations.Validator.Settings.CopyValuesOnValidate to true. For ASP.NET, this can be set during the ApplicationStart() event in global.asax as below.

public class Global : System.Web.HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

        ScissorValidations.Validator.Settings.CopyValuesOnValidate = true;
    }
}

Previous: Setting Up the Page

Next: Client-Side Validations