Results 1 to 3 of 3

Thread: MVC, RegularExpressionAttribute problem.

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Apr 2005
    Location
    Debug.Print
    Posts
    3,885

    Question MVC, RegularExpressionAttribute problem.

    I am inheriting the RegularExpressionAttribute to create my own DataAnnotation for validating user input. It is not working for me.
    I wish to only allow hyphens, spaces and upper/lowercase letters.
    Regardless of what I input into the form on the MVC Web App, it shows the error message each time.
    What am I doing wrong?

    The custom DataAnnotation from the class is [NameValidation]

    Code:
        public class NameValidationAttribute : RegularExpressionAttribute
        {
            public NameValidationAttribute()
                : base(@"/^[a-zA-Z \-]+$/")
            {
                ErrorMessage = "{0} can only consist of letters and spaces. Please correct your input.";
            }
        }

  2. #2

    Thread Starter
    PowerPoster
    Join Date
    Apr 2005
    Location
    Debug.Print
    Posts
    3,885

    Re: MVC, RegularExpressionAttribute problem.

    I even went to www.regexr.com and I put in the following regex. Says it is valid because it highlighted the text in the form on that site. But, when using it in my code above, I still get the error message on the view. What am I missing?

    Code:
    /([A-Za-z\-])\w+/g

  3. #3
    Fanatic Member
    Join Date
    Oct 1999
    Location
    England
    Posts
    982

    Re: MVC, RegularExpressionAttribute problem.

    I do not believe this is the right expression. It does not validate a single character, it does validate underscores.
    Code:
    /([A-Za-z \-])\w+/g
    This is the right expression, but the problem is how it is being assigned.
    Code:
    [a-zA-Z \-]+
    This does not work
    Code:
     public NameValidationAttribute() : base(@"/^[a-zA-Z \-]+$/")
    This does work, notice how the forward slashes are omitted before the ^ and after the $.
    Code:
     public NameValidationAttribute() : base(@"^[A-Za-z \-]+$")
    Just as a side note, you could assign the regular expression when declaring the attribute as below
    Code:
        
    public NameValidationAttribute(string Pattern)
        : base(Pattern)
    {
    }
    
    // Then specify the attribute on the property of the model  
    [NameValidation(@"^[A-Za-z \-]+$",ErrorMessage ="Not Valid Name")]
    public string Name { get; set; }
    To be honest, after all this work you are still only implementing the standard RegularExpressionAttribute and gaining nothing apart changing the name of the attribute.


    Things I do when I am bored: DotNetable

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width