Menu
  • HOME
  • TAGS

Mandatory validation for a subset of properties using data annotation

c#,validation,data-annotations

After some researches and your advices I have found a general strategy. Are you free to use external packages? Yes Add foolproof library to a solution Create a readonly property IsGroupRequired like public Boolean IsGroupRequired { get { return GroupItem1.HasValue == GroupItem2.HasValue && GroupItem2.HasValue == GroupItem3.HasValue && GroupItemNminus1.HasValue == GroupItemN.HasValue;...

Custom ValidationAttribute doesn't work. Always returns true

c#,data-annotations

The reason why your custom ValidationAttribute class isn't working is because WPF doesn't (by default) look into such classes when doing validation. The default mechanism for validation is implementing the IDataErrorInfo (available for .NET 4.0 and earlier) or INotifyDataErrorInfo (introduced in .NET 4.5) interfaces. If you don't want to implement...

MVC Model DataAnnotation [DataType(DateType.Date)] renders DatePicker but hides my value?

asp.net-mvc,date,model-view-controller,asp.net-mvc-5,data-annotations

I'm assuming you're also using the HTML 5 date input type, i.e. <input type="date">. The value for a date input type, must be an ISO formatted date: YYYY-MM-DD. The placeholder you see there is just the browser providing a more user-friendly display, but it's converting to/from the ISO format behind...

data val required not generated using Client Side Validation

c#,asp.net-mvc,data-annotations,client-side-validation

Can you have a look at the solutions provided for this question. MVC 4 client side validation not working Also another one is described in this blog...

EF Code First Data Annotations and Inheritance

mysql,entity-framework,entity-framework-6,data-annotations

I just went with using partial classes since it seems inherited classes have issues.

Programmatically validate using data annotations?

c#,entity-framework,data-annotations,validationattribute

Looks like I didn't realize, but the ValidationContext.MemberName property is read-write. I ended up using the following: public IEnumerable<ValidationResult> IValidatableObject.Validate( ValidationContext validationContext) { var context = new ValidationContext(this) { MemberName = "BirthDate" }; var dateResults = new List<ValidationResult>(); if (!Validator.TryValidateValue(this.BirthDate, context, dateResults, new[] { new RequiredAttribute { ErrorMessageResourceType = typeof(ValidationResx),...

mvc data annotation to restrict user to not allow only numeric numbers and special characters

regex,asp.net-mvc-4,data-annotations

You need to use a negative lookahead at the start. @"^(?![\W_]+$)(?!\d+$)[a-zA-Z0-9 .&',_-]+$" DEMO (?![\W_]+$) Negative lookahead asserts that the string won't contain only special characters. (?!\d+$) asserts that the string won't contain only digits. ...

Client validation in Razor views not working

c#,asp.net-mvc,razor,data-annotations

This path won't mean anything to a web browser: <script src="~/Content/scripts/jquery-ui-1.8.24.min.js" type="text/javascript"></script> The ~ notation is a server-side concept, referring to the application root directory. The browser won't know what to make of that. So I'm guessing none of the JavaScript files referenced with this notation are being loaded. You...

Hide some fields from view in ASP.Net MVC

asp.net,asp.net-mvc,asp.net-mvc-4,data-annotations,scaffolding

I would recommend to use ViewModels. That means you can map your db poco entity to physical representation of your View (known as ViewModel). Then, you can show whatever you want. When you do not want to update some columns, you can hide it using CSS or make it just...

Using Html.DisplayFor() outside of view or getting formatted property from DisplayFormat annotation

c#,asp.net,asp.net-mvc,razor,data-annotations

You can use a generic type for the method: public static string GetProductSnippet<T>(Product product, HtmlHelper<T> helper) { return helper.DisplayFor(p => p.ReleaseDate).ToString(); } var markup = GetProductSnippet<List<Product>>(product, helper); As for getting the code without the helper, you can get the implementation of the display helper from MVC source code and adjust...

how to validate dropdownlist using the DataAnnotation?

asp.net-mvc-4,data-annotations

There are 2 main issues with you code. First your trying to bind a <select> to a property which is List<SelectListItem>, but a <select> only posts back a single value type which cant be bound to List<SelectListItem> so the property is null and validation fails. Your properties need to be...

C# [using] as data annotation

c#,asp.net-mvc,namespaces,data-annotations

Why I can't use like this? From the MSDN documentation, a using directive does not give you access to any namespaces that are nested in the namespace you specify. And is there any way to use a namespace just for a method? like: There is no way to do...

How to restrict a multiline textbox to accept only one Number?

regex,asp.net-mvc,data-annotations

^(?!(?:.*?\d+\b){2})[a-zA-Z0-9 ]+$ You can try this regex .See demo.It uses lookaehad to make sure string has exaclt one number.See demo. https://regex101.com/r/wU4xK1/8...

Custom required attribute with C# & Web API and using private access modifier with validation context

c#,data-annotations,web-api,requiredfieldvalidator

You don't have to use the _Mappings Property, the code below checks if the related Attribute has a value that matches what you specified in the attribute, If there is a match then it checks to see if the Property you are validating has a value. protected override ValidationResult IsValid(object...

Always fails when use the regex

regex,asp.net-mvc,data-annotations

In C# regex, unlike PHP, JavaScript, and some other languages, you do not have to use delimiters. [RegularExpression(@"\[email protected]\.com", ErrorMessage = "You must use your mycompany email to register")] The regex is anchored in a RegularExpressionAttribute and it will match a string that \w+ - Starts with alphanumeric, 1 or more...

Entity Framework 6 Reusing Data Annotations

c#,asp.net-mvc,entity-framework,data-annotations

Here's a solution I've come up with after considering the other possible solutions posed. It's based on finding the following article... http://jendaperl.blogspot.co.uk/2010/10/attributeproviderattribute-rendered.html My reasons for this over others are stated at the bottom of this post. Having an existing Data Model class of... public class UserAccount { [Display(Name = "Username",...

Can I get the custom error message used with data annotation on controller MVC?

c#,asp.net-mvc,data-annotations

You can do this using reflection, better used as an extension method: public static T GetAttribute<T>(this object instance, string propertyName) where T : Attribute { var attrType = typeof(T); var property = instance.GetType().GetProperty(propertyName); return (T)property .GetCustomAttributes(attrType, false).First(); } Usage: var errorMessage = client.GetAttribute<EmailAddressAttribute>("Username").ErrorMessage; ...

MetadataType attribute removs when edmx change

c#,asp.net-mvc,entity-framework,data-annotations

Use partial classes for that. Never modify a designer code file, since it's reproduced from scratch on every change. Read here...

MVC models' unique field Create-Edit Complication

asp.net,asp.net-mvc,asp.net-mvc-4,data-annotations

You could use the AdditionalFields property of RemoteAttribute to include EmployeeId in the validation. Then in your action method, if EmployeeId=null validation fails if a matching email is found, otherwise only check for matching emails where its a different EmployeeID

Regular expression for alphanumeric and underscore c#

regex,asp.net-mvc-5,data-annotations

Try this regex written under the regexr.com site. Criteria - alphanumeric,underscore and space. http://regexr.com/3agii...

MaxLength attributes depends on consuming class

c#,asp.net-mvc,data-annotations,maxlength

After some reading and lots of googling, I concluded that the underlying issue is that the meta data set by data attributes is static. Therefore the nested class properties cannot have different meta data even if consumed by different classes. The solution is to put the meta data on the...

Add Attributes to instance of object at runtime

c#,razor,model-view-controller,data-annotations,custom-attributes

I don't think you'll be able to accomplish this exactly, since attributes are static metadata. Can attributes be added dynamically in C#? A possible workaround could be to create your own custom Attribute that implements all the possible validations (MaxLength, Range, etc.) and have some trigger attached to the object...

Entity Framework - Check if property is mapped

c#,entity-framework,data-annotations,inotifypropertychanged

My problem was in my Foo class. I apparently had a floating [NotMapped] attribute far above the property I was checking. I ended up using something like this: protected void FooPropertyChanged(object sender, PropertyChangedEventArgs e) { var notMapped = typeof(Foo).GetProperty(e.PropertyName).GetCustomAttributes(typeof(NotMappedAttribute), false); if (notMapped.Length == 0) { UnitOfWork.Value.GetRepository<Foo>().Update(MyFoo); } } ...

Map or Copy DataAnnotations to another class

c#,asp.net,.net,model-view-controller,data-annotations

That won't work - AutoMapper copies only values. DataAnnotations need to be defined on each class because they define extra behaviour. The easiest way to reduce code duplication would be to create a class containing the "Kunden" data and let your viewmodel inherit from it, only adding the extra fields...

How to validate GET url parameters through ModelState with data annotation

c#,validation,rest,web-api,data-annotations

Create your own model... public class YourModel { [//DataAnnotation ...] public string taxCode { get; set; } [//DataAnnotation ...] public string requestCode { get; set; } } And change your signature of your server side controller: [HttpGet] public IHttpActionResult GetActivationStatus([FromUri] YourModel yourmodel) { if (ModelState.IsValid) { ... } } If...

Best Practices ViewModel Validation in ASP.NET MVC

c#,asp.net-mvc,validation,data-annotations,unobtrusive-validation

To answer your 3th question first: No there is no easier way then what you are doing. Two lines of code to get it working can hardly be easier. Although there is a plug-in you could use, like explained in the question unobtrusive validation not working with dynamic content Your...

MVC ModelState IsValid reports true when should be false

c#,asp.net-mvc,entity-framework,validation,data-annotations

I've downloaded your code and included it in a new empty MVC4 application. The bad news is that it didn't work. The good news is that it can work perfectly with just an small change: In your controller, either remove the Bind attribute of the Register POST action parameter or...

Get the current length from StringLengthAttribute in C#

asp.net-mvc,validation,data-annotations

Finally, the solution is quite simple: public class MinMaxLengthAttribute : StringLengthAttribute { int? _stringLength = null; public MinMaxLengthAttribute(int minimum, int maximum) : base(maximum) { SetErrorMessage(); MinimumLength = minimum; } void SetErrorMessage() { ErrorMessage = "{0} must contain {2} až {1} characters." + " It contains " + (_stringLength ?? -1)...

Having Range attribute and one extra number

c#,range,data-annotations

You need to define your own validation attribute in that situation. You can directly inherit from ValidationAttribute class or inherit RangeAttribute and override a few methods. class CustomRangeAttribute : RangeAttribute { private double special; public CustomRangeAttribute(double minimum, double maximum, double special) : base(minimum, maximum) { this.special = special; } public...

DataAnnotations with EDMX EF 6.0 does not work

entity-framework,attributes,metadata,data-annotations

I believe a similar question has been answered here. When you try to access a MetadataType property attribute, you have to get to the MetadataType using reflection, and not simply the class that uses the MetadataType. There is an explanation in the link I provided and an example of how...

Jquery Validation Don't work on Submit if Submit has some Code

jquery,asp.net-mvc,jquery-validate,data-annotations,unobtrusive-validation

Quote OP: "I am using MVC Data Anotation with jquery validation for validating my form. It works perfectly on submit but if I write some code on submit click, it doesn't validate it. Why so? Where am I wrong? I am using jquery.validate.unobtrusive.min.js and jquery.validate.min.js" The jQuery Validation plugin automatically...

Entity Validator using DataAnnotations

.net,entity-framework,data-annotations

Wrong TryValidationObject overload. Try this one. var subsessionIsValid = Validator.TryValidateObject( subSession, validationContext, validationErrorsList, true); ...

How to display the error message for DataAnnotations

c#,entity-framework,mvvm,data-annotations,ef-database-first

I ended up fixing this myself by binding to a property in the viewmodel rather than the model itself and adding the annotations to the view model rather than trying to extend and clutter the model. Thinking about it, I probably should have done that first.......

MVC : How to use database to drive validation attributes, or ALTERNATIVES?

asp.net-mvc-4,metadata,data-annotations,custom-model-binder

I'd asked this on the FluentValidation forums also and the lack of answers here as well as the advice against using Fluent from there led me to find my own solution (I understand this almost certainly means I'm doing something really bad / unusual / unnecessary!) What I've ended up...

Why do inherited data annotations stop working?

c#,asp.net-mvc-5,data-annotations

Well I'd expect server side validation to continue to work but the reason client-side validation stops working is that you have to tell ASP.NET which adapter to use to generate the client-side validation JavaScript. If you're not actually changing the behaviour of RequiredAttribute you could just use its adapter. Put...

{System.InvalidOperationException: The parameter conversion from type 'System.String' to type 'System.Collections.Generic.KeyValuePair

asp.net-mvc,razor,data-annotations

An IEnumerable<SelectListItem> is required for a dropdown list, but that is an interface and not a solid implementation... e.g. "what sort of IEnumerable should I create when I serialise? I have no idea!" Change that member to a List<SelectListItem> [Required] [Display(Name = "Gender")] public string selectedGender { get; set; }...

Need to map an EF entity property to a column using another property's name

ef-code-first,entity-framework-6,data-annotations

Try commenting out this line: EFHelpers.StringHelper.DisableUnicodeForAllEntityStrings(Me, modelBuilder) It is not part of the framework, happens on modelCreating, and it looks like it might do something to Strings (it's called String helper)....

The specified value does not conform to the required format yyyy-MM-dd

jquery,asp.net-mvc,google-chrome,datetime,data-annotations

The specifications for the HTML5 date picker state that the date must be in the format yyyy-MM-dd (ISO format). This means that you DisplayFormatAttribute must be [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyInEditMode = true)] public string MyDate { get; set; } Alternatively you can manually add the format using @Html.TextBoxFor(m => m.MyDate,...

Range Attribute for Dates

c#,data-annotations,date-range,asp.net-mvc-5.2,displayattribute

You can use a little formatting on the error message attribute: [RangeDate(ErrorMessage = "Value for {0} must be between {1:dd/MM/yyyy} and {2:dd/MM/yyyy}")] public DateTime anyDate { get; set; } ...

ASP.NET Data Annotations Regular Expression: Don't allow following characters in Name: \, /, :, *, ;,

c#,asp.net-mvc,data-annotations

I finally ended up with this solution thanks to great suggestions from people on this thread: [Required] [RegularExpression(@"^[^\\/:*;\.\)\(]+$", ErrorMessage = "The characters ':', '.' ';', '*', '/' and '\' are not allowed")] public string Name { get; set; } ...

MVC 5 data annotation validation compare attribute for password field does not work client side

model-view-controller,asp.net-mvc-5,data-annotations

I removed the [DataType.Password] from Model property of password field and then data-annotation client validation works like a charm

How to retrieve Data Annotation Alias(“tablename”) and Alias(“field name”) from ServiceStack ORMLite?

c#,servicestack,data-annotations,ormlite-servicestack

You can query this from OrmLite's ModelDefinition that's created for every POCO Table, e.g: var modelDef = typeof(Account).GetModelMetadata(); var tableName = modelDef.ModelName; var idName = modelDef.PrimaryKey.FieldName; Which in both cases will return the [Alias] if it exists....

Entity Framework Code First Foreign Key issue

c#,entity-framework,ef-code-first,foreign-keys,data-annotations

It is possible set by yourself the Id of BaseCard, but first you have to use Fluent Api to specify this and the one-to-many relationship. Also, at this way, you don't have to specify attributes in your model classes. Your model classes would be like this: public class BaseCard {...

(MVC) Regex: starts with, ends with and can only contain

regex,asp.net-mvc,data-annotations

Just remove the lookahead at the very end of your regex and you should be done. /^[A-Za-z][A-Za-z|.| |'|-]*[A-Za-z]$/g What you want to make sure, is that the very last letter of your match is a letter, so there is no need to have a lookahead. You can just match it...

MVC5 - Data Annotations - Client Side Validation Not Happening?

asp.net-mvc,asp.net-mvc-4,data,data-annotations

I found my problem. In my BundleConfig.cs I have the following: bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.min.js", "~/Scripts/jquery-ui-1.10.4.min.js", "~/Scripts/jquery.base64.js" )); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate.min.js", "~/Scripts/jquery.validate.unobtrusive.min.js" )); But, what I didn't realize is that the jqueryval bundle DOES NOT get loaded in the _Layout.cshtml file by default. So I needed to add it, as follows:...

Get other property attributes while validating a custom attribute

.net,validation,reflection,data-annotations,custom-attributes

After finding this thread, I have found the way to get the display attribute. protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var otherProperties = validationContext.ObjectType.GetProperties(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance).ToList(); //To get the assigned MetaDataAttribute for the class var metaData = validationContext.ObjectType.GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType<MetadataTypeAttribute>().ToArray().FirstOrDefault();...

Do Data Annotations only work with ASP.NET?

c#,wpf,mvvm,data-annotations,ef-database-first

In your class, add annotations to the properties and inherit from PropertyChangedNotification. Also, implement the INotifyPropertyChanged and IDataErrorInfo interfaces.

Displaying html-formatted text for enum values in MVC

c#-4.0,model-view-controller,enums,data-annotations,display-templates

I found an easy answer. I just had to use a unicode value to accomplish this. m³ ...

Double error message with remote data annotation mvc 5

asp.net-mvc,double,data-annotations

I just fixed the problem i just removed the remote annotation on the lastName, the functionality is still the same but the second error was removed. I thought i had to add the same annotation on the second field to be validated too.

Automapper with Column Order Data Annotation

ef-code-first,asp.net-mvc-5,data-annotations,entity-framework-6,automapper-3

Order can't be negative one. And since an answer needs at least 30 characters let me add MSDN's doc: Gets or sets the zero-based order of the column the property is mapped to. ...

Radio Button For Enum (DataAnnotation)

c#,enums,radio-button,data-annotations,html-helper

Unfortunately there is no out-of-the-box control for this like you get with @Html.EnumDropDownListFor. You can, however, create an editor template for radio button enums like mentioned in the following: MVC5: Enum radio button with label as displayname (see selected answer).

MVC - localise [Display] attribute, but not just Name

c#,asp.net-mvc,resources,data-annotations

I found the solution to my problem, and it's been a mistake in another piece of code. I was getting the Prompt value through reflection. It's a big difference in getting the value through the public field Prompt and GetPrompt() method: DisplayAttribute attr = GetTheAttribute(); string firstVal = attr.Prompt; string...

ASP.NET MVC: Why Range Data Annotation is not working on checkbox in client side?

c#,asp.net-mvc,asp.net-mvc-4,data-annotations

I finally came with this solution: public class EnforceTrueAttribute : ValidationAttribute, IClientValidatable { public override bool IsValid(object value) { if (value == null) return false; if (value.GetType() != typeof(bool)) throw new InvalidOperationException("can only be used on boolean properties."); return (bool)value == true; } public override string FormatErrorMessage(string name) { return...

DateTime Regex Validator

c#,jquery,regex,asp.net-mvc,data-annotations

If you insist on regex solution, I modified yours a bit (to restrict it to rules you provided):...

Code First Optional One-To-One Relationship

c#,asp.net-mvc,entity-framework,ef-code-first,data-annotations

In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to...

Using C#, how do I inject a return statement into a method?

c#,validation,model,data-annotations

Thanks to the help from the comments above, I produced the following code which does exactly as I wanted: The Extension Method: public static void Validate<T>(this T entity) { var errors = new List<ValidationResult>(); var result = ""; try { var context = new ValidationContext(entity, null, null); Validator.TryValidateObject(entity, context, errors,...

Automatically generating data annotations from camel case field names

c#,asp.net-mvc,data-annotations

Using a combination of the information found on the blog here, and the excellent camel-case split regex here, I was able to work this out. The concept is that you create a custom flavour of the default DataAnnotationsModelMetadataProvider. In the case where a property does not have a display name...

How do I Localize a Class Display Name

c#,localization,data-annotations

The solution is to create your own Display Name attribute. The following worked for me and could be made more generic by passing the Resource file name which in my case I simply hardcoded. using System.ComponentModel; using System.Resources; namespace SCC.Case.Entities { /// <summary> /// Provides a class attribute that lets...

How to correctly use Data Annotations to select which Items should be returned by the Web API?

data-annotations,asp.net-web-api2,circular-reference,ef-database-first

It seems that the update statement doesn't turn lazy loading on: db.Configuration.LazyLoadingEnabled = true; The related items would only be returned if I went into debug mode and loaded the related data when hovering over the object (seems strange), but basically it was staying in lazy loading = false mode....

Validation context not checking Validation Attributes

c#,validation,data-annotations

Try this var result = Validator.TryValidateObject(t, context, validationResults, true); You must make use of the validateAllProperties parameter in TryValidateObject. Set it to true. that's it then range validator should work as expected. hope this helped!...

Jquery Scroll to elements without Ids, only by data attributes

javascript,jquery,animation,scroll,data-annotations

I would recommend using jQuery's filter() instead of trying to concatenate it in. I also think the $("html,body") part is where it's bugging out for you. Otherwise your code is actually correct: var someGuid = "0003"; var $scrollTo = $("li.commentInList.topLevelComment").filter(function(i){ return $(this).data('commentid') === someGuid; }); $(document.body).animate({ scrollTop: $scrollTo.offset().top }, 1000);...

How to relate model property to same model in ASP.NET MVC?

asp.net-mvc,entity-framework,data-annotations,foreign-key-relationship,ef-fluent-api

Something like in your class public class User : Identity { public int Id { get; set; } public string UserName { get; set; } public string Email { get; set; } public string Name { get; set; } // this is the self referential part public int? RegisteredById {...

Add attribute to property

asp.net-mvc-4,attributes,data-annotations

K Foolproof did the job. public string Description { get; set; } public bool IsRequired { get; set; } [RequiredIfTrue("IsRequired", ErrorMessage = "Elabe")] public string RequiredString { get; set; } This says that when the property IsRequired == true --> the property RequiredString must not be empty and will receive...

How can I test for [AllowHtml] attribute within an editor template?

asp.net-mvc,data-annotations,mvc-editor-templates

I believe you'll have to do some heavy lifting in the template like: var allowHtmlAttribute = this.ViewData.ModelMetadata .ContainerType .GetProperty(this.ViewData.ModelMetadata.PropertyName) .GetCustomAttributes(typeof(AllowHtmlAttribute), false) .Select(a => a as AllowHtmlAttribute) .FirstOrDefault(a => a != null); and now that I think about it, a Extension Method would be great! public static class ModelMetadataExtensions { public...

RangeAttribute with Enum

c#,validation,data-annotations

Try this: isValid = Validator.TryValidateObject(this, validationContext, results, true); There is no problem with enums, you just miss the last parameter - validateAllProperties Type: System.Boolean true to validate all properties; if false, only required attributes are validated....

Remote validation doesn't work when property to validate is inside a modal Bootstrap

asp.net-mvc,asp.net-mvc-3,data-annotations,bootstrap-modal,remote-validation

In your second example, the html generated will be name="MyOtherModel.Nickname" so the key/value pair posted back will be MyOtherModel.Nickname:yourValue. Change the controller method to public JsonResult CheckNickname([Bind(Prefix="MyOtherModel.Nickname")]string nickname) which will effectively strip the prefix and bind correctly to parameter nickname Note also that the modal usage may be a problem...

Using the name data annotation vs hard coding in view

c#,entity-framework,data-annotations

The benefit of DisplayAttribute is localization like the code below. [Required] [Display(Name = "First Name", ResourceType = typeof(YourResources)))] public string FirstName { get; set; } ASP.NET MVC 3 localization with DisplayAttribute and custom resource provider has some good answers about localization and different way to achieve it....

Apply Data Annotations Server Side Only

asp.net-mvc,validation,data-annotations

Switch off client-side unobtrusive validation on a field by field basis by overriding the data-val='true' Data Annotation attribute for the field in the view. @Html.TextBoxFor(m => m.Title, new { @data_val = "false" }) ...

MVC client side validation for PhoneAttribute

javascript,asp.net-mvc,forms,data-annotations,unobtrusive-validation

Guided by article Adding Client-Side Validation Support for PhoneAttribute or Fighting the Lookbehind in JavaScript function initPhoneValidator() { $.validator.addMethod("phone", function (value, element) { if (this.optional(element)) { return true; } var reverseValue = $.trim(value).split("").reverse().join(""); var reverseRegEx = new RegExp("^(\\d+\\s?(x|\\.txe?)\\s?)?((\\)(\\d+[\\s\\-\\.]?)?\\d+\\(|\\d+)[\\s\\-\\.]?)*(\\)([\\s\\-\\.]?\\d+)?\\d+\\+?\\((?!\\+.*)|\\d+)(\\s?\\+)?$", "i"); var match = reverseRegEx.exec(reverseValue);...

RegularExpression DataAnnotation to validate string EndsWith particular domain name

regex,asp.net-mvc,validation,data-annotations

Like i said in my comment, you need ti escape the dots present in your regex and also you need to add .* before @. [RegularExpression(@".*@mydomain\.co\.uk$", ErrorMessage = "Must be a @mydomain.co.uk email address")] ...

ASP.NET MVC ValidationAttribute causes invalid client side validation rules

jquery,asp.net-mvc,jquery-validate,data-annotations,unobtrusive-validation

One way that i know is this: [Range(typeof(decimal), "0", "79228162514264337593543950335")] public decimal Amount { get; set; } Meh-ish, but this is a real deal. And decimal MaxValue is 79228162514264337593543950335. https://msdn.microsoft.com/en-us/library/system.decimal.maxvalue(v=vs.110).aspx...

Using Foolproof RequiredIf with an Enum

c#,enums,data-annotations,foolproof-validation

Given that your method NotificationMethodID is returning an int, the reason your check is failing is that, in c#, each enum is its own type, inheriting from System.Enum. I.e. if you do var value = NotificationMethods.Email; string s = value.GetType().Name; You will see s has the value "NotificationMethods" not "Int32"....

KendoUI Grid Default Value with Data Annotation

asp.net-mvc,kendo-ui,kendo-grid,data-annotations,kendo-asp.net-mvc

if you defined the columns in the grid manually, you need to set the default value like this despite you defined the default value in the annotation or not @(Html.Kendo() .Grid() .DataSource( d=> d.Ajax() .Model(m=>{ m.Field(f=>f.YourField).DefaultValue(YourValue); })) ) so for the auto-generated columns you can try the following @(Html.Kendo() .Grid()...

MVC ignores DataType on overriden model property when DisplayFor is used

asp.net-mvc,razor,data-annotations,display-templates

What's the Model in declared in your view? The abstract or child? It uses reflection to read the attribute based on the model declared so: @model PostBase @Html.DisplayFor(m => m.Body) Will work differently to @model MessagePost @Html.DisplayFor(m => m.Body) the first of these will apply the [Required] only. It's bound...

Comparing DateTimes across Entities

c#,entity-framework,data-annotations

Data Annotations are good for triggering simple validation on individual properties but aren't good for model level validation. You should implement IValidatableObject on you entity. Something like this: public class Grievance: IValidatebleObject { public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (FileDate < Incident.IncidentDate ||(HearingDate.HasValue && HearingDate.Value < Incident.IncidentDate)) { yield return...

VS2013 MVC - Display name not working on some fields

asp.net-mvc,data-annotations

After some more investigation, it seems that for some reason the scaffolded .cshtml contains a literal string for any fields that from related tables.

Data annotation validation for an invalid string

c#,data-annotations

I think you want to create a custom attribute. Something like this: class YourValidationAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) // Do your validation check....and return a ValidationResult return ValidationResult.Success; } } Then annotate your class with it: [YourValidationAttribute] public string Country { get set }...

About Enum and DataAnnotation

c#,enums,data-annotations,asp.net-mvc-5.2,displayattribute

MVC doesn't make use of the Display attribute on enums (or any framework I'm aware of). You need to create a custom Enum extension class: public static class EnumExtensions { public static string GetDisplayAttributeFrom(this Enum enumValue, Type enumType) { string displayName = ""; MemberInfo info = enumType.GetMember(enumValue.ToString()).First(); if (info !=...

How to use DataAnnotations attributes in mvc4 to check for a valid input

asp.net,asp.net-mvc-4,data-annotations

You can associated a specific error message with a [Required] attribute. Note the [RegularExpression] attribute is not required (its effectively just repeating the [Range] attribute) [Required(ErrorMessage = "Must be numeric")] [Range(1,int.MaxValue, ErrorMessage="Value must be at least 1")] public int SortOrder { get; set; } The reason you were getting "The...

Can I dynamically add Data Annotation to a view model for unit-testing?

c#,unit-testing,tdd,data-annotations

You cannot do this as far as I can tell. Would be great if someone could prove me wrong. See this question and this question....

How to change the default error message of built-in ValidationAttributes?

c#,validation,data-annotations

Just create your own version of the [Required] attribute that has a default message that you want. If you only want to use a custom error message have it inherit from RequiredAttribute so you can take advantage of the same IsValid logic public class MyRequired : RequiredAttribute { public MyRequired()...

Data annotation to check dependent property is value

c#,asp.net-mvc,data-annotations

No. There is no such native annotation. You can make your own, which will take as a paramter the name of the property on which the validation depends, and then when applying, pass the appropriate property name. The way to do this is to create a custom annotation class deriving...