-1

When I set value from server side to prop has a validation attribute "MaxLength", the application not throw exception.

public class Student
    {
        public Guid Id { get; set; }

        [MaxLength(40,ErrorMessage ="too long")]
        public string Name { get; set; }
    }


  [HttpPost("AddStudent")]
        public IActionResult AddStudent()
        {
            string studentName = System.IO.File.ReadAllText(@"C:\StudentName.txt");

            Student student = new Student()
            {
                Id = Guid.NewGuid(),
                Name = studentName, // Name larger than 40 char
            };            

            //Add student to DB

            return Ok();
        }

I expect throwing exception directly while I set not valid value

  • 1
    `expect throwing exception` where do you expect that and why? Validation doesn't run by itself, otherwise you'd never be able to create any objects. All would be invalid until you stopped changes. When ASP.NET Core handles a request, the runtime itself validates the objects before calling the action – Panagiotis Kanavos Sep 01 '23 at 11:26

2 Answers2

2

MaxLength is a data annotation attribute in MVC. It will not work when you create the Student object manually unless you explicitly call the model validator. By the way, it gets executed automatically if you bind the student class property values from request parameters / query string.

-1
public class Student
    {
        public Guid Id { get; set; }

        //[MaxLength(40, ErrorMessage = "too long")]
        private string _name;
        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                if (value.Length > 40)
                {
                    throw new Exception("too long");
                }
                _name = value;
            }
        }
    }