简体   繁体   中英

C# ASP MVC - A field that only accepts hexadecimal values for colors

I'm making an admin input panel.

Admin will have an option to create a custom color using an hexadecimal value such as #0000ff or #008000, etc.

Right now, I´m using this in my model:

[Required(AllowEmptyStrings = false, ErrorMessage = "Please enter the color")]
public string Color { get; set; }

How can I validate so the admin can only put hexadecimal values here?

And most importantly, is this really necessary? I heard that the browser tends to ignore false hex codes Why does HTML think “chucknorris” is a color?

I would say that it is beter to validate your inputs then relay on custom behaviour of browsers.

You can validate your field more or less with following attribute:

public class HexColorAttribute : ValidationAttribute
{
    private string _errorMessage;

    public HexColorAttribute(string errorMessage)
    {
        _errorMessage = errorMessage
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var colorHexStr = (string)value;
        var valid = Regex.IsMatch(colorHexStr, "#[0-9a-fA-F]{6}");
        if(valid)
        {
              return ValidationResult.Success;
        }
        else
        {
              return new ValidationResult(_errorMessage)
        }

    }

and then:

[Required(AllowEmptyStrings = false, ErrorMessage = "Please enter the color")]
[HexColor("Color has to have format '#123456'")]
public string Color { get; set; }

It is working similarly to Required attribiute. Take a look at source code of RequiredAttribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM