Skip to main content

How to: Validate Cards

  • 2 minutes to read

The example below validates data entered by an end user into a card. Validation is implemented within the ASPxCardView.CardValidating event handler. In this example, validation fails in the following cases:

  • one or more field values are empty;
  • Contact Name and/or Company Name fields are set to a single character.

The ASPxCardView.StartCardEditing event is handled to display errors (if any) within the edited card when an end user switches to edit mode.

protected void ASPxCardView1_CardValidating(object sender, ASPxCardViewDataValidationEventArgs e) {
    // Checks for null values.
    foreach (CardViewColumn column in ASPxCardView1.Columns) {
        CardViewColumn dataColumn = column as CardViewColumn;
        if (dataColumn == null) continue;
        if (e.NewValues[dataColumn.FieldName] == null)
            e.Errors[dataColumn] = "Value cannot be null.";
    }
    // Displays the card error row if there is at least one error.
    if (e.Errors.Count > 0) e.CardError = "Please fill out all fields.";

    if (e.NewValues["ContactName"] != null && e.NewValues["ContactName"].ToString().Length < 2) {
            AddError(e.Errors, ASPxCardView1.Columns["ContactName"], 
            "Contact Name must be at least two characters long.");
    }
    if (e.NewValues["CompanyName"] != null && e.NewValues["CompanyName"].ToString().Length < 2) {
        AddError(e.Errors, ASPxCardView1.Columns["CompanyName"],
            "Company Name must be at least two characters long.");
    }
    if (string.IsNullOrEmpty(e.CardError) && e.Errors.Count > 0) 
        e.CardError = "Please correct all errors.";
    }

void AddError(Dictionary<CardViewColumn, string> errors, CardViewColumn column, string errorText) {
    if(errors.ContainsKey(column)) return;
    errors[column] = errorText;
}

protected void ASPxCardView1_StartCardEditing(object sender, ASPxStartCardEditingEventArgs e){
    // Validates the edited card if it isn't a new card.
    if (!ASPxCardView1.IsNewCardEditing)
        ASPxCardView1.DoCardValidation();
    }
}