jwaliszko / expressiveannotations Goto Github PK
View Code? Open in Web Editor NEWAnnotation-based conditional validation library.
License: MIT License
Annotation-based conditional validation library.
License: MIT License
Hi,
I have a custom RadioButtonList editor template that I use like:
[UIHint("RadioButtonList")]
public string MyProperty { get; set;}
....
It doesn't seem like I'm able to use the client-side expresssive annotations in this case. When I move the code out of the editor template and into the calling Razor view everything works fine. Maybe I'm missing something?
Any help is appreciated.
Thanks,
Jason
Hi, just started using your impressive library, and have a question regarding the RequiredIf validatior.
Assuming a MVC5 form with a model with 2 properties:
[RequiredIf("LastName == null",
ErrorMessage = "At least first or last name should be provided.")]
public string FirstName{ get; set; }
[RequiredIf("FirstName == null",
ErrorMessage = "At least first or last name should be provided.")]
public string LastName { get; set; }
Right now, to make the second validation message to dissapear, I have to 1.) Place the pointer in the second textbox. 2.) Remove the pointer from the second textbox.
I would like to be able to test if two dates are fall on the same calendar date.
I added a utility function called IsSameDay, but I am curious if there is a way to do this currently.
As a side note how do you run your javascript unit tests?
Thanks for the great lib!
-justin
Sorry if this is already covered elsewhere.
Is it only possible to reference properties of the current class, or is it possible to reference properties from a sibling class in a slightly more complex class structure?
i.e. Is it possible for a RequiredIf expression on ChildClass1's Property A to reference ChildClass2's Property A? Example below fails.
public class RootClass
{
public virtual ChildClass1 One { get; set; }
public virtual ChildClass2 Two { get; set; }
}
public class ChildClass1
{
[RequiredIf(@"Two.A == 'SomeValue'")]
public string A { get; set; }
}
public class ChildClass2
{
public string A { get; set; }
}
I need a insensitive requiredif value comparison
City=="PARIS" same as City=="Paris"
How can i do this ?
UI in Nuget says:
v 2.4.5
Dependencies
Newtonsoft.Json >= 4.5.11
My project has 6.0.8.18111 referenced
While it runs fine in Visual Studio, come deployment time it fails.
Adding in
to the web config doesn't work (just makes the error not tell you the assembly version) which makes me suspect there's another dependency further down as well.
Thanks for a great script. I've been using this in every asp.net MVC application since I discovered it.
I was recently facing a problem when I included this with another library that uses a global use strict statement. Due to the use of the with statement, the application was throwing errors in the console since the with statement cannot be used in strict mode
I fixed the issue by modifying that other library to use strict mode only within the context of that script. But I thought I would call your attention to it, so that you might consider removing the deprecated keyword.
Thanks again.
First thanks for a great extension - it's working really well for me, but I have one issue.
I have this on my view model:
[RequiredIf("QuestionTypeAsString == 'SingleSelect' && Skipped == false && RefusedToAnswer == false", ErrorMessage = "Please complete the answer or select one of the options to skip the question")]
public int[] SelectedOptionsAnswer { get; set; }
This is posted via a set of checkboxes or radio buttons in the view, and I want to make sure one is selected.
When I step through the code SelectedOptionsAnswer is null, but the model state is valid. Is there a way to get this attribute working with arrays please?
Say I have a checkboxlist and I want to check if a value if checked and then make sure another field is required... is this possible?
[Display(Name = "Favorite Color Apple"), RequiredIf("FavoriteFruit == 'apple'", ErrorMessage = "Favorite Color Apple is required")]
HI
It seems that the RequiredIf returns an empty string in the member validation result.
I checked it with your samples?
Any idea?
Thanks
Is it possible to change the settings exposed on the API from another script so that I don't have to modify the code in expressive.annotations.validate.js? Setting "ea.settings.dependencyTriggers = undefined;" in my own script changes the property value but does not change the behavior. As far as I can tell from the code, the dependencyTriggers events are bound to the controls at page load and not re-bound after settings are changed. Is there a way to trigger re-binding after changing the settings in my script?
Hey Jaroslaw,
Thanks again for this awesome library. I'm using requireJS with my project (as a lot of others are) so I thought I'd let you know how to hook up the EA script with requireJS, and you can do whatever you may with that information.
First step is to alias all the paths for the scripts you need:
requirejs.config({
paths: {
"jquery": "lib/jquery-1.8.2",
"jquery-validate": "lib/jquery.validate",
"jquery-validate.unobtrusive": "lib/jquery.validate.unobtrusive",
"ea": "lib/expressive.annotations.validate"
}
});
We also need to tell require what the various dependencies are:
requirejs.config({
shim: {
"jquery-validate": ["jquery"],
"jquery-validate.unobtrusive": ["jquery", "jquery-validate"],
"ea": { deps: ["jquery", "jquery-validate", "jquery-validate.unobtrusive"], exports: "ea" },
}
});
Note: you should probably concatenate these two calls to requirejs.config.
Now, to load ExpressiveAnnotations you can simply include this line in your script:
var ea = require("ea")
I understand WHY you've got this.
What I can't understand is why it's triggering for me.
I've got a POCO "order object" with a list of POCO "line objects"
Neither inherit from anything else.
For the line object I have a "RequiredIf" attribute on 11 of the 12 properties (property 12 is "ProductCode")
All saying "ProductCode != null"
8 of the 11 are string, but as I remove the attributes, the error is thrown on the next property to be rendered out, regardless of type
My List contains 2 line objects, one of which has a null product code
Are these attributes support automatic generation of client side validation scripts? (Jquery validation rulset with sependency I assume...)
Hi Jaroslaw,
I would like to know if it was possible to combine the two - "AssertThat" and "RequiredIf". This is the example of the business rule that I would like to code:
Model Class
FirstName
LastName
EnrollmentDate
Validation - The EnrollmentDate should be greater than today's date if the FirstName = "John" and LastName = "Doe".
The first name and last name are not required fields.
I stumbled upon a validation requirement today that called for the validation assertion of a property only if some condition is met. A similar concept to RequiredIf. I wonder if an overlooking a feature that covers such a case. What are your thoughts?
Hi,
I have a module with some properties:
public bool HaveHolder { get; set; }
[RequiredIf("HaveHolder == true")]
public int? AffinityID { get; set; }
public Affinity Afinitty { get; set; }
[RequiredIf("HaveHolder == true")]
public int? HolderNIF { get; set; }
In View the AffinitiyID is rendered with a input select, and the HolderNIF with a input type text (numeric). The input type text fired the validation if my checkbox HaveHolder is not check, but the input select don't...
This is part of the View for the AffinityID property:
<div class="form-group">
@Html.LabelFor(model => model.AffinityID, "AffinityID", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("AffinityID", null, "-- select one option --", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.AffinityID, "", new { @class = "text-danger" })
</div>
</div>
Example in https://github.com/JaroslawWaliszko/ExpressiveAnnotations not working.
Not work:
[RequiredIf("GoAbroad == true")]
This works:
[RequiredIf(DependentProperty = "GoAbroad", TargetValue = true, ErrorMessage = "You have to authorize us to make contact.")]
I'm using JsonConvert.DefaultSettings
in my application to set application-wide default JSON serialization settings (e.g. setting ContractResolver
to CamelCasePropertyNamesContractResolver
). This causes the client-side validation to fail (specifically in this case due to camel-cased field names ending up in the data- attributes) because ExpressiveAnnotations isn't opting out of using default settings.
Since ExpressiveAnnotations relies on specific JSON formatting for client-side validation, it should follow the recommended approach for libraries by opting out of user-specified default settings. This can be accomplished by creating a JsonSerializer
instance instead of using JsonConvert.SerializeObject()
as per the Json.NET blog post on the subject:
Because there are cases where JSON should not be customized, e.g. a Facebook or Twitter library, by default JsonSerializer won’t use DefaultSettings, providing an opt-out for those frameworks or for places in your application that shouldn’t use default settings.
This would make it more resilient to unexpected behavior.
I am attaching a datepicker to an element and setting the element to readonly="readonly". The RequiredIf attribute works properly if I remove the readonly attribute but will not work with the readonly attribute present.
disabled="disabled" should not validate, but readonly="readonly" should.
AssertThat does not support comparing Guid or Guid? values
I made some changes to support Guids, and create PR #22
Is it possible for a property to be RequiredIf an IEnumerable property contains an item?
I am able to do this on the server side with a custom function ie...
public class ItemInCollectionTest
{
[RequiredIf("HasRequired(Items)")]
public string ExtraField { get; set; }
IEnumerable<Item> Items { get; set; }
public bool HasRequired(IEnumerable<Item> items)
{
return items.Any(i => i.ExtraFieldOption == ExtraFieldOptions.Required);
}
}
public class Item
{
public ExtraFieldOptions ExtraFieldOption { get; set; }
public string Name { get; set; }
}
public enum ExtraFieldOptions
{
Required,
NotRequired
}
On the client-side however there is no Items field. Items are transformed into n number of Items[X]. This causes extractValue to fail to find a com elemet and throw an exception at line 260.
I have written a custom client side function and added it to ea, but unfortunately this exception causes my code to not be called.
Thanks for the help,
Justin
ExpressiveAnnotations isn't showing validation-errors on the clientside when used with Ajax-Forms and PartialViews. The validation on the server is going fine but when the PartialView is returned no validation-errors are shown. I created a small solution to explain the problem, am I doing something wrong or is there no support for Ajax.BeginForm?
See this sample project: https://github.com/GVersluiss/ExpressiveAnnotationIssue
Thanks in advance,
Gerben
If IsNewOrder == true, Adults must be greater than 0. When IsNewOrder == false, Adults does not need to be greater than 0. But when IsNewOrder == false and Adults == 0, the following error is still displayed. Any suggestions? Thanks!
[AssertThat("IsNewOrder == true && Adults > 0", ErrorMessage = "At least one adult is required")]
I have a lot of RequiredIf attributes with enum Target values. Which is the correct way to write these in 2.0?
[RequiredIf("WithholdingType == " + (int)WithholdingType.FederalRateSchedule)]
OR
[RequiredIf("WithholdingType == " + WithholdingType.FederalRateSchedule)]
I initially pulled in the full nuget package but realised i only needed the dll as I handle my own validation on the client.
When I removed that and than added the core package instead... it would not work. I had to remove the dll that it had referenced in the lib45 folder in favour of the one in the lib40 folder.
This is in a .net 4.5 project.
I only want the date check to occur if NcLicensedToPractice == 'true' but for some reason it's always firing regardless of the NcLicensedToPractice value...
[AssertThat("NcLicensedToPractice == 'true' && (LawSchoolGraduationDate < NcLicensedDate)", ErrorMessage = "Law School Graduation Date must be < NC Licensed To Practice Date")]
many thanks!
I downloaded the source code to try to track down an issue I was having in my project with the application crashing when I was trying to use the RequiredIf attribute on a property of my View Model.
The exception: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
I adjusted the code a bit and started digging and this is the first loaded exception that comes up:
*Inheritance security rules violated by type: 'DotNetOpenAuth.Messaging.OutgoingWebResponseActionResult'. Derived types must either match the security accessibility of the base type or be less accessible".
It happens in the DLL DotNetOpenAuth.Core.
I'v already modified ExpressiveAnnotations.Analysis.Parser.ExtractMemberExpression to loop through the assemblies rather than one LINQ statment.
You had:
var enumTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Where(t => t.IsEnum && t.FullName.EndsWith(name)).ToList();
I modified it to figure out what assembly was causing the issue and temporarily solved the issue with this:
List<Type> enumTypes = new List<Type>();
foreach (System.Reflection.Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
Type[] matchedTypes = null;
try
{
matchedTypes = a.GetTypes().Where(t => t.IsEnum && t.FullName.EndsWith(name)).ToArray();
}
catch (System.Reflection.ReflectionTypeLoadException loaderError)
{
try
{
string outerEx = loaderError.Message;
//Parse only the assemblies that were loaded
matchedTypes = loaderError.Types.Where(t => t != null && t.IsEnum && t.FullName.EndsWith(name)).ToArray();
}
catch (System.Reflection.ReflectionTypeLoadException innerLoaderError)
{
//Abort any additional errors
}
}
if (matchedTypes != null && matchedTypes.Length > 0)
enumTypes.AddRange(matchedTypes);
}
I have a model that is generated X number of times. I basically want to require validation on a textbox field (CountyCollection_0__PatentRegistrationNumber) if a hidden field's value = true (this is toggled true/false if a specific checkboxlist item is checked).
Many thanks in advance as always!
model:
[Display(Name = "Patent Registration Value")]
public String PatentRegistrationValue { get; set; }
[AssertThat("IsPatentRegNumberRequired()", ErrorMessage = "Patent Registration Number is required")]
[Display(Name = "Patent Registration Number")]
public String PatentRegistrationNumber { get; set; }
view:
If you checked Patent Law, what is the Registration #:
<input class="patent-item" id="patentItem" name="patentItem" type="hidden" value="0" />
<input id="CountyCollection_0__PatentRegistrationValue" name="CountyCollection[0].PatentRegistrationValue" type="hidden" value="false" />
<input data-val="true" data-val-assertthat="Patent Registration Number is required" data-val-assertthat-constsmap="{}" data-val-assertthat-expression=""IsPatentRegNumberRequired()"" data-val-assertthat-fieldsmap="{"PatentRegistrationValue":"string"}" id="CountyCollection_0__PatentRegistrationNumber" name="CountyCollection[0].PatentRegistrationNumber" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="CountyCollection[0].PatentRegistrationNumber" data-valmsg-replace="true"></span>
client script:
//expressive annotations custom client function
ea.addMethod('IsPatentRegNumberRequired', function () {
//local declare
var bStatus = false;
//get current item
var currentItem = $(this).parents("div").find(".patent-item");
//get patent reg value textbox
var patentBox = $('#CountyCollection_' + currentItem.val() + '__PatentRegistrationValue');
//check value
if (patentBox.val() == "true")
{
//set if true
bStatus = true;
}
//return status
return bStatus;
});
This seems to be an issue with Linq and what types it determines are arithmetic.
For me Expression.Divide
was the killer, but there may be other issues as well.
You can trace through the Expression.Divide
code here:
http://referencesource.microsoft.com/System.Core/a.html#e48196c57cc9f07c
It calls IsArithmetic
which is here:
http://referencesource.microsoft.com/System.Core/Microsoft/Scripting/Ast/TypeUtils.cs.html#d279c9ec254c1933
Byte is not listed in IsArithmetic
.
A normal byte works because it is up-cast to a Double.
Client side validation methods has a jquery ajax request to web service. The request is executed on every key up event (as the event happens) which is too frequent. How can I specify a delay mechanism?
Hey,
First off, I've been looking a lot for something like Expressive-Annotations and it works great!
I've done this (a single line):
[AssertThat(@"(nDisplayMode!=3 && nAThreshold<=95 && nAThreshold>=5)
|| (nDisplayMode==3 && (nAThreshold<=95 && nAThreshold>=5 || nAThreshold<=-5 && nAThreshold>=-95))",
ErrorMessage = "A Threshold is out of range")]
and it's working just fine, but than i wanted to be a little more specific with the error message, so I've done this (4 lines):
[RequiredIf("nDisplayMode==3")]
[AssertThat("((nAThreshold>=5 && nAThreshold<=95) || (nAThreshold>=-95 && nAThreshold<=-5))",
ErrorMessage = "A-Threshold is out of range (-95)-(-5) or (5-95)")]
[RequiredIf("nDisplayMode!=3")]
[AssertThat("nAThreshold>=5 && nAThreshold<=95",
ErrorMessage = "A-Threshold is out of range (5-95)")]
but only the first 2 lines of RequiredIf-AssertThat seem to work. Is there any other way for me to do this a bit more specific?
thanks,
I would like to be able to test if two dates are fall on the same calendar date.
I added a utility function called IsSameDay, but I am curious if there is a way to do this currently.
As a side note how do you run your javascript unit tests?
Thanks for the great lib!
-justin
That case is directly related to this thread (more context there).
[RequiredIf(ArrayContains(Item, Values))]
I was thinking about something like that, although I'm not fully aware of all pros/cons of such a solution yet:
js:
typeHelper = {
array: {
...
tryParse: function(value) {
if (typeHelper.isString(value)) {
var array = JSON.parse(value);
if (array instanceof Array) {
return array;
}
}
return { error: true, msg: 'Given value was not recognized as a valid array.' };
},
...
tryParse: function(value, type) {
switch (type) {
case 'datetime':
return ...
...
case 'array':
return typeHelper.array.tryParse(value);
c#:
internal static class Helper
{
public static string GetCoarseType(Type type)
{
...
if (type.IsArray)
return "array";
Then, anyone who would like to use that built-in array type, should provide appropriate DOM field from where it can be extracted (like in any other case), but this time using templates, since there is no out-of-the-box construction in ASP.MVC for that, so create:
/Type/ArrayTemplate.cshtml:
@using Newtonsoft.Json
@model int[] // or any other /Type/
@Html.Hidden("", JsonConvert.SerializeObject(Model))
and put this in the form:
@Html.EditorFor(model => model.Values, "IntArrayTemplate")
then, respective ArrayContains
function, e.g. IntArrayContains
(not necesairly built-in) would work:
public bool ArrayContains(int? value, int[] array)
{
return value != null && array.Contains((int)value);
}
ea.addMethod("ArrayContains", function(value, array) {
return $.inArray(value, array) >= 0;
});
for such a usage cases:
[RequiredIf("IntArrayContains(Item, Values)")]
By looking at proposed solutions (in related thread), which I like, I'm just thinking what would be the advantage of this since everything is sent to client in json most times. But still, it there will be cases when no json is used (but xml?), or we just want to handle the parsing by ourselves, maybe it is enough to just expose complex
type parsing like it is done for date
, so:
api = {
settings: {
parseComplex: undefined,
parseDate: undefined
...
typeHelper = {
...
tryParse: function(value, type) {
switch (type) {
...
case 'datetime':
...
default:
if (type === 'complex' && typeof api.settings.parseComplex === 'function')
return api.settings.parseComplex(value);
return { error: true };
}
The disadvantage is that there is only one parseComplex
method to override, so each custom case related to eventual multiple complex types should be somehow distinguished there. But still such cases are rather rare.
The idea with dynamic typeHelpers is also attractive (taken from related thread):
ea.addTypeHelper("sometype", function (value) {
// parse in any way you want and return
});
[CustomTypeHelper("sometype")]
// or maybe [TypeHelper("sometype")] or [ClientTypeHelper("sometype")] etc.
public IEnumerable<int> Values { get; set; }
We can add it all.
This is rather not an option, but we can also change nothing - by choosing that way though developers are going to handle such stuff by themselves, in a way shown by my answers at the beginning of related thread.
Hi,
At the moment we can discover only at runtime when If an annotation is not correct. Is there a way to let's say grab a list of types with annotations and compile them to check whether they are correct or not? Having this available would allow us to create a code convention type of unit test which would shorten the feedback cycle.
The operators <, <=, > and >= should be implemented for Enums. It should compare the numeric underlying value of the Enum.
Hi there,
I am new to MVC and was trying to use your expressive.annotations.validate library/scripts. I have tried but I cannot figure out a solution to the following problem:
'jQuery is not defined' and the file that is in error is expressive.annotations.validate.js, (Line 489). I have attached pictures to illustrate the same.
Any help will be greatly appreciated,
Thanks
Jason
Hi,
thanks for this great library!
I´m working on a portable version that can be used with Xamarin and mobile products. So there is no System.ComponentModel.DataAnnotations and the Reflection stuff is a little bit different.
I´v made everything portable with conditional building. And all (shared) files in the PCL version are just links to the files in the normal project.
I will write some Validator that can be used in a portable app/library when i have more time.
I´v created a PCL version of the unit tests too. Both PORTABLE and non portable unit tests are all working fine. If you like it would be nice if you could merge it with your branch or make a new one. I try to keep up with your master branch. It would be more easier if the #if #endifs would be in your master as well. Without i have a lot of merge conflicts that must be fixed manually.
Greetings Muraad
I'm sure this is by design but v2.3.0 no longer exposes the private API via the ___6BE7863DC1DB4AFAA61BB53FF97FE169
property so I guess this is more of an enhancement request than a bug.
I am looking for support for JSON-serialized properties and/or support for extending the type parsing via a public API.
I have a model for which I want to compare a value to a list of values using RequiredIfAttribute
and a custom ListContains
method.
public class BasicModel
{
public bool ListContains(int? value, IEnumerable<int> list)
{
return list != null && list.Contains(value.GetValueOrDefault());
}
[Required]
public int? ReasonId { get; set; }
[RequiredIf("ListContains(ReasonId, ReasonIdsRequiringOtherInfo)")]
public string ReasonOther { get; set; }
public IEnumerable<int> ReasonIdsRequiringOtherInfo { get; set; }
}
ReasonIdsRequiringOtherInfo
is rendered to the browser as a hidden input with the value as serialized JSON.
In the past I was able to inject support for serialized JSON data in fields into EA via the following script (which would also allow my ListContains
method to work client-side):
(function ($, ea) {
ea.addMethod("ListContains", function (value, list) {
return $.inArray(value, list) >= 0;
});
// undocumented API - may break in future versions of Expressive Annotations
var typeHelper = ea.___6BE7863DC1DB4AFAA61BB53FF97FE169.typeHelper;
typeHelper.complex = {
tryParse: function (value) {
var result;
try {
result = JSON.parse(value);
} catch(ex) {
result = { error: true, msg: 'Given value was not recognized as valid JSON.' };
}
return result;
}
};
var oldTryParse = typeHelper.tryParse;
typeHelper.tryParse = function (value, type) {
switch (type) {
case 'complex':
return typeHelper.complex.tryParse(value);
default:
return oldTryParse(value, type);
}
};
}(jQuery, window.ea));
This workaround also allowed me to keep the default expressive.annotations.validate.js file unchanged, which makes updating via NuGet much easier.
If there is a better or alternative solution I would also be interested in that.
Update -- This is working in ExpressiveAnnotations.MvcWebSample I will have to dig a little deeper to see what is going on with my implementation
If a field has the same name as an enum for instance
public Stability Stability { get; set; }
[RequiredIf("Stability.High")] public bool AwareOfTheRisks { get; set; }
""Stability.High":numeric" is added to the data-val-requiredif-typesmap and nothing to the data-val-requiredif-enumsmap
I found couple of issues in expressive.annotation.validate.js
I have updated js file to get these worked for my appilcation. however, it would be nice to get package updated as well.
Thanks.
Hi,
after update to version 2.1.1 every query to database throws exception "Sequence has more than one element". Even simple var elements = db.Elements.ToList();
throws exception. It doesn't matter whether the model uses ExpressiveAnnotations or not.
When I rollback to v 2.1.0 everything is ok.
I don't know if this only happens to me or maybe this is a well known problem :)
Best regards,
Calfy
Hi Waliszko,
I have a sample model like below:
[RequiredIf("Test == null", ErrorMessage = "Test validation")]
[AssertThat("Test <= 0", ErrorMessage = "Test validation")]
public decimal Test { get; set; }
and a view:
@Html.TextBoxFor(g => g.Test)
@Html.ValidationMessageFor(g => g.Test)
When I start the page, the exception throws with the exception message like this: "Parse fatal error. The binary operator Equal is not defined for the types 'System.Double' and 'System.Object'."
Could you please take a look on this problem? I could not find any example with decimal data type on your sample project.
Thank You.
Hi,
We have a set of e2e Selenium based tests that we run in parallel on our build server. Since we started using ExpressiveAnnotations we can see every now and then the following error which we've never seen on our local dev machines where we run tests only sequentially. To be honest I have no idea where to start re debugging this problem. Any hints would be appreciated.
View model:
[Required]
[DisplayName("Has Deck Gear?")]
public bool DeckGear { get; set; }
[DisplayName("Number of Deck Gear")]
[Validation.RequiredIf("DeckGear", ErrorMessage = "Required if ship has a deck gear")]
public int? NumberOfDeckGear { get; set; }
Error:
I want to set validation requirements on multiple items from the same dropdownlist (MembershipType) and if either option is selected then enable the requirement..
a single item works:
[RequiredIf(DependentProperty = "MembershipType", TargetValue = "paralegal-regular", ErrorMessage = "NCCP Number is required")]
but how can I pass in multiple items from the list control? I would like to be able to do something like below specifying multiple option items from the same parent control:
[RequiredIf(DependentProperty = "MembershipType", TargetValue = new[] object ("paralegal-regular", "paralegal-provisional"), ErrorMessage = "NCCP Number is required")]
OR
[RequiredIf(DependentProperty = "MembershipType", TargetValue = "paralegal-regular||paralegal-provisional", ErrorMessage = "NCCP Number is required")]
OR
RequiredIf(DependentProperty = "MembershipType", TargetValue = "paralegal-regular*paralegal-provisional", ErrorMessage = "NCCP Number is required")]
Is this possible? I also tries the expression with no luck either. Many thanks!
[RequiredIfExpression(Expression = "{0} || {1}", DependentProperties = new[] { "MembershipType", "MembershipType" }, TargetValues = new object[] { "paralegal-regular", "paralegal-provisional" }, ErrorMessage = "NCCP Number is required")]
btw awesome extension!
Not sure this is exactly a bug in your code, perhaps something you hadn't considered or came across so far...
In expressive.annotations.validate.js, line 62, where the string value coming from the input is passed to Date.parse(), if that string is in UK format (DD/MM/YYYY), Date.parse successfully returns a numeric milisecond value which is then successfully used to create a date object. The code does not error, but the date object returned does not have the expected value.
The specific problem I had here was that I was comparing two date fields, one >= the other, and with these resulting incorrect dates it gave the impression that sometimes the validation was working and sometimes it was not.
I can work around this temporarily by switching the 'DD' and 'MM' components of my 'value' string between the existing lines 61 and 62 as in my application all dates use that format.
The following attribute will not work as expected if the DependentProperty is rendered as a radio list.
[RequiredIf(DependentProperty = "Field", TargetValue = true, ErrorMessage = "First name is required")]
public string FirstName { get; set; }
public bool Field { get; set; }
<input id="Field_false" type="radio" name="field" value="false" />
<input id="Field_true" type="radio" name="field" value="true" />
This can be fixed by modifying Helper.extractValue and Helper.compare:
extractValue: function(form, dependentProperty, prefix) {
var dependentField = $(form).find(':input[name="' + ModelPrefix.append(dependentProperty, prefix) + '"]');
var dependentValue = $(dependentField).val();
if (dependentField.is(":radio"))
{
dependentValue = dependentField.filter(":checked").val();
}
else if (dependentField.is(":checkbox"))
{
dependentValue = dependentField.is(':checked');
}
return dependentValue;
},
compare: function(dependentValue, targetValue) {
if (typeof dependentValue == 'string' || dependentValue instanceof String)
dependentValue = dependentValue.trim();
if (typeof targetValue == 'string' || targetValue instanceof String)
targetValue = targetValue.trim();
// this is probably not generic enough
if (dependentValue == "true")
dependentValue = true;
else if (dependentValue == "false")
dependentValue = false;
return (dependentValue == targetValue) || (dependentValue != '' && targetValue == '*');
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.