How to use Data Annotations?

Gauges

Stay Connected for Heartfelt Updates!


Interesting snippet from C#, ASP.NET and MVC, that uses the ValidationAttribute

Ever wanted to add validation to your MVC view, well look further for more details.

The ValidationAttribute will help you validate your model and server-side properties. As a programmer, you will need to add certain rules or attributes to the properties, such as required, string length, range and change the display property name. The example has a special attribute that limits the amount of words the user can type into a field.

You are required to inherit from ValidationAttribute, in order to use the error message and IsValid method of the attribute. Once you have those, you can set in the constructor, the message and max value. Then override the IsValid method and check the property for the amount of words. I used split and length methods to check against the max words.

If all is fine, return success, otherwise give the user the error message you set in the constructor.

The programmer will need a lot of flexibility in validating their model and view, this snippet can help you avoid writing a lot of extra client side code.

A lot of the credit goes to Scott Allen course on Building Applications with ASP.NET MVC4.

public class MaxWordsAttribute : ValidationAttribute
    {
        public MaxWordsAttribute(int maxWords)
            : base("{0} has too many words.")
        {
            _maxWords = maxWords;
        }

        protected override ValidationResult IsValid(
            object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                var valueAsString = value.ToString();
                if (valueAsString.Split(' ').Length > _maxWords)
                {
                    var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                    return  new ValidationResult(errorMessage);
                }
            }
            return ValidationResult.Success;
        }

        private readonly int _maxWords;
    }

    public class Reviews : IValidatableObject
    {
        [Range(1,10)]
        [Required]
        public int Rating { get; set; }

        [Required]
        [StringLength(1024)]
        public string Desc { get; set; }

        [Display(Name = "User Name")]
        [DisplayFormat(NullDisplayText = "anonymous")]

        [MaxWords(1)]
        public string UserName{ get; set; }

        public IEnumerable Validate(ValidationContext validationContext)
        {
            if (Rating < 2 && UserName.ToLower().StartsWith("cookies"))
            {
                yield return new ValidationResult("Sorry, cookies, you can't do this");
            }
        }
    }

One response to “How to use Data Annotations?”

Leave a reply to Mohammad Khan Cancel reply

  1. Mohammad Khan Avatar

    I find your article berry berry interesting.

    Liked by 1 person

I can be your coach in the following areas: Art, Nutrition, Knowledge Management
  • Grandpa Birthday Card 2023
  • Grandpa Birthday Card 2023
  • Grandpa Birthday Card 2023
  • Valkyrie’s of Abundence IINYC 12.8.21
  • Day Two: Write a List Afanc IINYC
  • I write because and draw zillo star wars
  • IINYC Prompt fudge 6.16.21
One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$1.00
$3.00
$5.00
$1.00
$3.00
$5.00
$12.00
$13.00
$14.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

ad art artblog artinfluence artist artjournal balance bunny character coda concept conceptartist creative writing creativity Design digitalart digital art doodle dragon draw drawing drawing plan environment everydayinspiration Featured fineart IINYC illustration imaginative illustrators know life live stream love mind painting plan rock studies see ski story thoughts time travel twitch WordPress

Give A Line Chain donate to make your mark on the line art.

Venmo Vye 3 black
Advertisements

Discover more from Vyechi | Personal Growth & Mindfulness

Subscribe now to keep reading and get access to the full archive.

Continue reading