Search code examples
asp.net-mvcmodel-validation

Asp.Net MVC model validation with default text in textbox


I am trying to validate input control in Asp.Net MVC. The below code checks if Project name is null and throws validation. I will have some default text in textbox on page load. I have a scenario to check if project name is not null and project name is not "Test Project". Can I do in similar scenario?

[Required(ErrorMessage = "Select Project Name.")]
[DisplayName("Project Type: ")]
public string SelectedProjectName { get; set; }

Solution

  • you can write your own Custom validator here is an example.

        public class ProjectNameValidation : ValidationAttribute
    {
    
        public ProjectNameValidation()
        {
    
        }
    
        //private const string errorMsg = "{0} must at least {1} or not more than {2}";
    
        public override bool IsValid(object value)
        {
            if (value != null && value !="Test Project")
            {
                return true;
            }
    
            return false;
        }
    }