I have a simple view model class for MVC2 that has a MagicItem property:
public class VoodooViewModel {
[Required(AllowEmptyStrings = false,
ErrorMessage = "The Magic Item is required")]
[RegularExpression(#"^[^-]*$",
ErrorMessage = "Hyphens are not allowed in Magic Items.")]
public string MajorModel { get; set; }
}
I am simply trying to disallow hyphens in this property, but for the life of me I can't get it to work. Can anyone see what I'm doing wrong (the RequiredAttribute is working fine)?
To my eyes, the regex I have says "from the beginning of the string to the end, match anything that isn't a hyphen". I have tested this in the Regex tester here, and it works - but not in my code. I can't get the error to show no matter how many hyphens I put in it.
Like a tool, I forgot to check in the controller's action method to see if the ModelState was valid or not:
public ActionResult UberController(VoodooViewModel vvm)
{
if (!ModelState.IsValid) return View(vvm); //turns out this line is important
(...yaddayaddayadda...)
}
Thanks to Darin for pointing me in the right direction.
Related
I'm trying to use the "RegularExpression" DataAnnotation validaiton in my model. My problem is even for the valid input I provide for the field containing the validation, the regex doesn't match and it fails.
I try to test the same valid input with the regex in a stand-alone console app and I find it gets through.
My point is, when regex is being used in dataannotation as validation, it considers all input as bad input. What am I missing here?
My regex is for checking comma-seperated email IDs. Here is my model:
public partial class BuildModel
{
public Int64 ConfigID { get; set; }
[Required(ErrorMessage = "Please select a stream!")]
public String Name{ get; set; }
[RegularExpression(#"^(([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)(\s*(;|,)\s*|\s*$))", ErrorMessage = "Please enter valid email IDs separated by commas")]
public string EmailIDs { get; set; }
public bool IsActive { get; set; }
}
Note: The "Required" data-annotation validation works just fine. It is just the Regex one, that won't work!
As far as i understand you just have problem within your Regex.
To validate emails separated by comma you can use this regex:
^( *[\w+-.%]+#[\w-.]+\.[A-Za-z]{2,4}( *, *)? *)+$
Check in in here.
You must the jquery.validate.min.js and jquery.validate.unobtrusive.min.js in your page without these libraries required annotation would not works.
I am using the regular expression for the Password field. Includes alpha-numeric string and md5.
[Required(AllowEmptyStrings = true)]
[RegularExpression(#"^(((?=.*\d)(?=.*[a-zA-Z]).{6,20})|([0-9a-f]{32}))$")]
[Display(Name = "Password")]
public string Password { get; set; }
And, I'd leave the field empty password. But ValidationMessage shows "This field is required."
message.Even if delete Required, it still gives the message.
Friends, how can I fix it?
Removing the Required attribute worked for me for server-side validation.
I've never used asp.net, and know nothing about it. However, 10 seconds on google tells me:
Make it nullable ( public string? Passsword { get; set; } )
I am trying to learn MVC4 and i've come to this chapter called validation.
I came to know about DataAnnotations and they have pretty neat attributes to do some server side validation. In book they have only explained about [Required] and [Datatype] attribute. However in asp.net website i saw something called ScaffoldColumn and RegularExpression.
Can someone explain what they are, even though I know little what RegularExpression does.
Also are there any other important validation attributes I should know?
Scaffold Column dictates if when adding a view based on that datamodel it should/not scaffold the column. So forexample your model's id field is a good candidate for you to specify ScaffoldColumn(false), and other foreign key fields etc.
I you specify a regular expression, then if you scaffold a new view for that model,edit customer for example, a regex or regular expression on field will enforce that entered data must match that format.
You can read about ScaffoldColumnAttribute Class here
[MetadataType(typeof(ProductMetadata))]
public partial class Product
{
}
public class ProductMetadata
{
[ScaffoldColumn(true)]
public object ProductID;
[ScaffoldColumn(false)]
public object ThumbnailPhotoFileName;
}
And about RegularExpressionAttribute Class you can read here.
using System;
using System.Web.DynamicData;
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(CustomerMetaData))]
public partial class Customer
{
}
public class CustomerMetaData
{
// Allow up to 40 uppercase and lowercase
// characters. Use custom error.
[RegularExpression(#"^[a-zA-Z''-'\s]{1,40}$",
ErrorMessage = "Characters are not allowed.")]
public object FirstName;
// Allow up to 40 uppercase and lowercase
// characters. Use standard error.
[RegularExpression(#"^[a-zA-Z''-'\s]{1,40}$")]
public object LastName;
}
We manage several ASP.NET MVC client web sites, which all use a data annotation like the following to validate customer email addresses (I haven't included the regex here, for readability):
[Required(ErrorMessage="Email is required")]
[RegularExpression(#"MYREGEX", ErrorMessage = "Email address is not valid")]
public string Email { get; set; }
What I would like to do is to centralise this regular expression, so that if we make a change to it, all of the sites immediately pick it up and we don't have to manually change it in each one.
The problem is that the regex argument of the data annotation must be a constant, so I cannot assign a value I've retrieved from a config file or database at runtime (which was my first thought).
Can anyone help me with a clever solution to this—or failing that, an alternative approach which will work to achieve the same goal? Or does this just require us to write a specialist custom validation attribute which will accept non-constant values?
The easiest way is to write a custom ValidationAttribute that inherits from RegularExpressionAttribute, so something like:
public class EmailAttribute : RegularExpressionAttribute
{
public EmailAttribute()
: base(GetRegex())
{ }
private static string GetRegex()
{
// TODO: Go off and get your RegEx here
return #"^[\w-]+(\.[\w-]+)*#([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$";
}
}
That way, you still maintain use of the built in Regex validation but you can customise it. You'd just simply use it like:
[Email(ErrorMessage = "Please use a valid email address")]
Lastly, to get to client side validation to work, you would simply add the following in your Application_Start method within Global.asax, to tell MVC to use the normal regular expression validation for this validator:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAttribute), typeof(RegularExpressionAttributeAdapter));
Checkout ScotGu's [Email] attribute (Step 4: Creating a Custom [Email] Validation Attribute).
Do you really want to put the regex in database/config file, or do you just want to centralise them? If you just want to put the regex together, you can just define and use constants like
public class ValidationRegularExpressions {
public const string Regex1 = "...";
public const string Regex2 = "...";
}
Maybe you want to manage the regexes in external files, you can write a MSBuild task to do the replacement when you build for production.
If you REALLY want to change the validation regex at runtime, define your own ValidationAttribute, like
[RegexByKey("MyKey", ErrorMessage = "Email address is not valid")]
public string Email { get; set; }
It's just a piece of code to write:
public class RegexByKeyAttribute : ValidationAttribute {
public RegexByKey(string key) {
...
}
// override some methods
public override bool IsValid(object value) {
...
}
}
Or even just:
public class RegexByKeyAttribute : RegularExpressionAttribute {
public RegexByKey(string key) : base(LoadRegex(key)) { }
// Be careful to cache the regex is this operation is expensive.
private static string LoadRegex(string key) { ... }
}
Hope it's helpful: http://msdn.microsoft.com/en-us/library/cc668224.aspx
Why not just write you own ValidationAttribute?
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute.aspx
Then you can configure that thing to pull the regex from a registry setting... config file... database... etc... etc..
How to: Customize Data Field Validation in the Data Model Using Custom
I want to use a regex validator to ensure that a certain string variable contains the substring "www.youtube.com/watch?v=", how would I do this?
[RegularExpression()]
[Required(ErrorMessage = "Youtube link is Required")]
[StringLength(100, ErrorMessage="Youtube link cannot exceed 50 characters")]
public string YoutubeLink { get; set; }
if (YoutubeLink.Contains("www.youtube.com/watch?v="))
{
//...
}
http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx
To use the RegularExpression attribute, you must specify the regex to use :
[RegularExpression("www\\.youtube\\.com/watch\\?v=", ErrorMessage = "Link is incorrect")]
public string YoutubeLink { get; set; }
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.regularexpressionattribute.aspx
I think what you might want is to check for any type of URL beginning. In that case, you would use #"^(http://)?(www\.)?youtube\.com/watch\?v=" as the regex string.
See an example of what this would match
Maybe much easier to use something like (Python):
ytlink = 'www.youtube.com/watch?v='
if(ytlink in yourfrase):
doYourLogic()
else:
smthElse()
Please correct me if I understood your question wrong.