I am a college student working with Asp.net MVC, I need to get a custom validation working that prevents input of specific characters e.g @#$%*, etc for a specific field. I know custom validations are a bit of a hassle but its what this part of the assignment calls for. I don't mind that I type with one finger but college takes all the fun out of learning any programming topic or language because I can't spend as much time as I want to learn proficient implementation of concepts. In this case custom Validation.
I created an InvalidCharsAttribute Class already and have already added the necessary field to the necessary class as follows...
InvalidCharsAttribute.cs
using System.ComponentModel.DataAnnotations;
namespace EnrollmentApplication.Models
{
public class InvalidCharsAttribute : ValidationAttribute
{
readonly string invalidChars;
public InvalidCharsAttribute(string invalidChars)
{
this.invalidChars = invalidChars;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
if ((string)value == invalidChars)
{
return new ValidationResult("Notes contains unacceptable characters");
}
}
return ValidationResult.Success;
}
}
Field to be checked for invalid characters
[InvalidChars(@"[*&%#@$^!]", ErrorMessage = "*&%#@$^! are invalid characters")]
public virtual string Notes { get; set; }
I am aware that if ((string)value == invalidChars)
is wrong I'm just not sure how to rewrite/add code so that my custom validation works. Simplest solution would be great.