So is an [Email] attribute built in ASP.NET MVC 3 or not?

前端 未结 4 1666
小鲜肉
小鲜肉 2021-02-20 03:11

The [Email] attribute was going to be built into ASP.NET MVC 3 as it was in futures? So is it now available or not? I guess it is quite a dumb question but I\'ve sp

相关标签:
4条回答
  • 2021-02-20 03:56

    If [Email] is supposed to be a data annotation for MVC models (like [Required]), then it's not built into ASP.NET MVC 3.

    All the model data annotations are found in the namesace System.ComponentModel.DataAnnotations. There you find classes like RequiredAttribute.

    Update:

    It's pretty easy to add the Email attribute:

    using System.ComponentModel.DataAnnotations;
    
    namespace YourNamespace
    {
        public class EmailAttribute : RegularExpressionAttribute
        {
            public EmailAttribute() : base("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
            {
            }
        }
    }
    

    What the best or correct regular expression for checking email addresses is, is a separate and long debate on the net. I'm not insisting that mine is either of it.

    0 讨论(0)
  • 2021-02-20 03:56

    [System.ComponentModel.DataAnnotations.EmailAddressAttribute] turns out to validate email by regex (at least in 4.5)

    0 讨论(0)
  • 2021-02-20 03:57

    You can include System.ComponentModel.DataAnnotations and use

        [DataType(DataType.EmailAddress)]
        public String ToAddress { get; set; }
    
    0 讨论(0)
  • 2021-02-20 04:00

    Take a look at this, http://dataannotationsextensions.org/. It has both server side and client side validation capabilities. It uses this regex underneath.

    new Regex(@"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
    
    0 讨论(0)
提交回复
热议问题