Silverlight RIA: Validate Entity Server Side

If you are working with Validating a Entity , Simple Meta Data Validation is not always enough , you might have to do a server side validation, and it is really simple
Along with regular metadata add a Custom Validation Attribute which has type of class where your validation logic resides and String name of the Validation Function

[Required(ErrorMessage="Client Name is Required")]
[StringLength(256)]
[DisplayName("Client Name")]
[CustomValidation(typeof(ClientValidations), "ValidateClientName")]
public string ClientName { get; set; }

and a sample function for validation would be

public static ValidationResult ValidateClientName(string ClientName, ValidationContext context)
        {
            Models.DB.Client client = (Models.DB.Client)context.ObjectInstance;
            Web.Models.DB.PortalDataContext pc =new Models.DB.PortalDataContext();
            var existing = pc.Clients.Where(c => c.ClientName == ClientName && c.Id != client.Id && c.Status == true);
            if (existing.Count() > 0)
            {
                return new ValidationResult("Invalid Client Name as the Client Name already Exists", new string[] { "ClientName" });
            }
            return ValidationResult.Success;
        }

Leave a Reply