Validate model on specific string values
you can use reqular expression like this:
[RegularExpression("M|F", ErrorMessage = "The Gender must be either 'M' or 'F' only.")]
public string Gender { get; set; }
but in my api it will show error message when i passed data so you can add
[StringLength(1, MinimumLength = 1, ErrorMessage = "The Gender must be 1 characters.")]
final code:
[StringLength(1, MinimumLength = 1, ErrorMessage = "The Gender must be 1 characters.")]
[RegularExpression("M|F", ErrorMessage = "The Gender must be either 'M' or 'F' only.")]
public string Gender { get; set; }
[Required]
[RegularExpression("value1|value2|value3|...", ErrorMessage = "YourMessageHere")]
public string Gender { get; set; }
To validate the Gender property I've created a custom validation attribute by creating a new class (attribute):
using System;
using System.Collections.Generic;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace MyProject.Models.Validation
{
public class StringRangeAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if(value.ToString() == "M" || value.ToString() == "F")
{
return ValidationResult.Success;
}
return new ValidationResult("Please enter a correct value");
}
}
}
In case anyone stumbles upon this thread in the future, I took it a little further and added a public string array property accepting the allowable values in the validation filter. This will allow you to provide a collection of valid strings in the attribute decorator.
This way, you now have a generic reusable attribute you can use anytime to limit a model string property to a predefined set of values. Since it's a validation attribute, you can decorate it with a more informative error message as well.
Example Usage:
public class Person {
[StringRange(AllowableValues = new[] { "M", "F" }, ErrorMessage = "Gender must be either 'M' or 'F'.")]
public string Gender { get;set; }
}
String Attribute:
public class StringRangeAttribute : ValidationAttribute
{
public string[] AllowableValues { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (AllowableValues?.Contains(value?.ToString()) == true)
{
return ValidationResult.Success;
}
var msg = $"Please enter one of the allowable values: {string.Join(", ", (AllowableValues ?? new string[] { "No allowable values found" }))}.";
return new ValidationResult(msg);
}
}