Here is the snippet of how the validation will work for Coma Separated Weekdays (0 to 6) in C# for ASP.NET Web API
public class WeekDaysAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var _weekDays = value as string; if (_weekDays.Length == 0) { return ValidationResult.Success; } //Check if the length is greater or not if (_weekDays.Length > 1) { if (!_weekDays.Contains(\',\')) { return new ValidationResult(\"The values must be comma separated\"); } //1st Check: Length should be 7 or less //& each character should not exceed more than 1 character //& the values should be integer if (_weekDays.Split(\',\').Length > 7) { return new ValidationResult(\"The length of the values should be less than or equals to 7\"); } else if (_weekDays.Split(\',\').Any(x => x.Length != 1)) { return new ValidationResult(\"The length of one or more provided values is greater than 1\"); } else if(_weekDays.Split(\',\').Any(x => !int.TryParse(x, out int parsedVal))) { return new ValidationResult(\"One or more provided values is not a valid integer value\"); } //2nd Check: Values should not repeat //If the count after distinct doesn\'t match the length then it have repeated elements else if (_weekDays.Split(\',\').Length != _weekDays.Split(\',\').Distinct().Count()) { return new ValidationResult(\"One or more values are repeated\"); } //3rd Check: Values should be between 0 and 6 else if (_weekDays.Split(\',\').Any(x => !(new List<int>() { 0, 1, 2, 3, 4, 5, 6 }).Contains(int.Parse(x)))) { return new ValidationResult(\"One or more values are not within the range between 0 and 6\"); } } //If it is 1 then check if it is an Integer value else if (!int.TryParse(_weekDays, out int parsedVal)) { return new ValidationResult(\"The value provided is not integer value\"); } //Check if it is within the week days range else if (!(new List<int>() { 0, 1, 2, 3, 4, 5, 6 }).Contains(int.Parse(_weekDays))) { return new ValidationResult(\"The value provided is not within the range between 0 and 6\"); } return ValidationResult.Success; } }
Leave a Reply