How to bind "readonly" in custom element in Aurelia? - binding

I have the following element in html file:
<require from="_controls/time-slot-slider"></require>
<time-slot-slider id="zeitraum" min="0" max="24" length="4" value="4"
value.two-way="functionConfig.startTime" if.bind="functionConfig.isAutomatic === true"
readonly.bind="!mayFunctionTestEditTime"></time-slot-slider>
Custom element is here(time-slot-slider.html):
<template class="range-slider time-slot">
<div>${duration}</div>
<input type="range" min.bind="min" max.bind="maxStart" step.bind="step" value.bind="value">
</template>
and time-slot-slider.ts :
import { bindable, customElement } from 'aurelia-templating'
import moment from 'moment/moment'
import Moment = moment.Moment
#customElement('time-slot-slider')
export class TimeSlotSlider {
#bindable public min: number = 0.0
#bindable public max: number = 24.0
#bindable public step: number = 0.5
#bindable public value: number = 0.0
#bindable public length: number = 4.0
public get maxStart (): number {
return this.max - this.length
}
public get from (): Moment {
return TimeSlotSlider.numberToMoment(this.value)
}
....
But readonly.bind doesn't work. I tried to bind readonly by
#bindable readOnly: boolean but I didn't have any success. How can I fix it?

I believe the problem is that you only apply readonly to your custom element:
<time-slot-slider readonly.bind="!mayFunctionTestEditTime"></time-slot-slider>
You've mentioned that you'd tried defining #bindable readOnly: boolean on the component's viewmodel, but I assume you had forgotten to apply it to the input itself. Obviously, just the presence of it won't magically cause it to be applied the the input, therefore like that, you basically have a property on your viewmodel that you don't use for anything.
The solution is to keep that #bindable readonly: boolean property on the VM but also bind its value to the actual input - essentially "forwarding" the value the component gets down to the actual control:
<input type="range" readonly.bind="readonly" ... />
It is also a good idea to give the properties a default value, see this answer (especially the comments) for details as to why.

Related

Render MVC form using reflection and Razor Tag Helper .Net 3.1

I want to create complicate form which will create structure of wizard, partial steps form, validation and submit. This structure have to use model attributes annotations to create one structure object over the model. So after reflection I have model and one other class with structure description. All properties within are strings with Fields which I have to pass on 'asp-for' tag helper. So part of the code is:
#foreach(var field in #group.Fields) {
<div class="col-12 col-md-6 col-lg-4">
<div class="form-group md-form md-outline">
<label asp-for="#field.Name" class="control-label"></label>
<input asp-for="#field.Name" class="form-control" />
<span asp-validation-for="#field.Name" class="text-danger"></span>
</div>
</div>
}
This is nor working because tag helper expect expression and generate wrong values which are not expected from me. The value in #field.Name is 'PostAddress.Street1'. If I replace all of "#field.Name" with "PostAddress.Street1" everything work properly how I expected.
It looks small issue but I'm trying many things and reading some theads in forums but didn't find the answer. What I tried:
Experiment 1
Tried to inherit InputTagHelper class from dotnet library and override property For but without success. It changed ModelExpression but no changes in interface. May be base class have some logic to skip this changed object or is not correct generated:
[HtmlAttributeName("asp-for")]
public new ModelExpression For
{
get
{
return base.For;
}
set
{
ModelExpression me = value;
if (value.Model != null)
{
var viewData = this.ViewContext.ViewData as ViewDataDictionary<AbnServiceModel>;
me = ModelExpressionProvider.CreateModelExpression<AbnServiceModel, string>(viewData, model => model.PostAddress.Street1);
}
base.For = me;
}
}
=================================================
2. Experiment 2
Try to get original implementation from .NET Core code and made some modification in code to fix the issue. But the code and dependencies with internal libraries were very complicated and I reject this idea.
Expiriment 3
Using HTML helpers
#Html.Label(#field.Name, "", new{ #class="control-label" })
#Html.Editor(#field.Name, new { htmlAttributes = new{ #class="form-control" } })
#Html.ValidationMessage(#field.Name,"",new { htmlAttributes = new{ #class="text-danger" } })
It render components correct into the browser but client side validation using jquery.validate.unobtrusive.js is not working. Not sure why.
Expiriment 4
Using HTML helpers:
#Html.LabelFor(m=>m.PostAddress.Street1, new{ #class="control-label" })
#Html.EditorFor(m=>m.PostAddress.Street1, new { htmlAttributes = new{ #class="form-control" } })
#Html.ValidationMessageFor(m=>m.PostAddress.Street1,"",new { htmlAttributes = new{ #class="text-danger" } })
The validation is working but class weren't applied well, may be my mistake. But other problem here is that I'm not using expression which is string which can get from model object. Also It doesn't catch all logic which is included in asp-for tag helper.
Experiment 5
Tried to create my own tag helper and using generator to create the content html. But this means that I have to implement all logic like helper in dotnet core to have all functionality which is same like Expiriment 2
So I didn't find good solution of this "simple" problem and lost some days to investigate and doing some code to resolve it. I'm surprised that no way to pass string variable with property name and it wouldn't work.
Can someone help me to fix this problem with real example? I didn't find the answer in all posts. I want to have all logic from asp-for tag helper but use variable to pass the expression. It cab be and tricky, just want to have some resolution to continue with my project.
Thank you
I resolved my issue.
Created one helper method:
public static class CommonHelperMethods
{
public static ModelExplorer GetModelExplorer(this ModelExplorer container, string field, IModelMetadataProvider modelMetadataProvider = null)
{
ModelExplorer result = container;
var fields = field.Split(".").ToList();
var match = Regex.Match(fields[0], #"(.+)\[(\d)+\]");
if (!match.Success)
{
fields.ForEach(x =>
{
result = result?.GetExplorerForProperty(x) ?? result;
});
}
else
{ //List have to create own Property browser
string proName = match.Groups[1].Value;
int idx = Convert.ToInt32(match.Groups[2].Value);
var model = ((IList)result?.GetExplorerForProperty(proName).Model)[idx];
var targetProperty = model.GetType().GetProperty(fields[1]);
var targetValueModel = targetProperty.GetValue(model);
var elementMetadata = modelMetadataProvider.GetMetadataForProperty(model.GetType(), fields[1]);
return new ModelExplorer(modelMetadataProvider, container, elementMetadata, targetValueModel);
}
return result;
}
}
And just override the tag helper class with this:
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace GetTaxSolutions.Web.Infrastructure.TagHelpers
{
[HtmlTargetElement("input", Attributes = ForAttributeName, TagStructure = TagStructure.WithoutEndTag)]
public class InputTextGtTaxHelper : InputTagHelper
{
private const string ForAttributeName = "asp-for";
[HtmlAttributeName("not-exp")]
public bool NotExpression { get; set; } = false;
[HtmlAttributeName(ForAttributeName)]
public new ModelExpression For
{
get
{
return base.For;
}
set
{
ModelExpression me = value;
if (NotExpression)
{
var modelExplorertmp = value.ModelExplorer.Container.GetModelExplorer(value.Model.ToString(), ModelMetadataProvider);
var modelExplorer = new ModelExplorer(ModelMetadataProvider, value.ModelExplorer.Container, modelExplorertmp.Metadata, modelExplorertmp.Model);
me = new ModelExpression(value.Model.ToString(), modelExplorer);
}
base.For = me;
}
}
public IModelExpressionProvider ModelExpressionProvider { get; }
public IModelMetadataProvider ModelMetadataProvider { get; }
public IActionContextAccessor Accessor { get; }
public InputTextGtTaxHelper(
IHtmlGenerator generator,
IModelExpressionProvider modelExpressionProvider,
IModelMetadataProvider modelMetaDataProvider) : base(generator)
{
ModelExpressionProvider = modelExpressionProvider;
ModelMetadataProvider = modelMetaDataProvider;
}
}
}
Also should skip original class in tag helper registration:
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#removeTagHelper Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers
#removeTagHelper Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers
#removeTagHelper Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers
#removeTagHelper Microsoft.AspNetCore.Mvc.TagHelpers.SelectTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers
#addTagHelper GetTaxSolutions.Web.Infrastructure.TagHelpers.*, GetTaxSolutions.Web
And when use model in expression just have to pass attribute 'no-exp' on input elements. Otherwise will work like original tag helper.
<input not-exp="true" asp-for="#field.Name" class="form-control" />
Also you have to do same with label, select and other used tag helpers which you want to support this way of model passing.

Internationalization in inList

i found this and it was very useful to what i want to do, but is there is way to make what in the inList follow the Grails Internationalization
Thanks
i found workaround , i think it may help ..
1. toString()
As you know, the scaffolded screens just output values in selects and dropdowns through the toString() method of the shown object. We can construct each enum with a hardcoded translation and have toString() return that value.
class Product {
enum Status {
AVAILABLE("Beschikbaar"), SOLD_OUT("Uitverkocht")
final String value
Status(String value) {
this.value = value
}
String toString() {
value
}
}
String name
Status status
static constraints = { name blank: false, unique: true }
}
The actual names of the enum now only appear in the generated HTML:
<select name="status" required="" id="status" >
<option value="AVAILABLE" >Beschikbaar</option>
<option value="SOLD_OUT" >Uitverkocht</option>
</select>
2. MessageSourceResolvable
By now you’ll probably understand above hardcoded solution works for just one language, one hardcoded in the enum itself – which will cause problems when in a month from now your application actually needs to support a 2nd language :-) So how do we leverage the fact that we have already have message_XX.properties where we’ve put our other message keys?
Use the underlying Spring framework. Have our enum implement org.springframework.context.MessageSourceResolvable e.g. like this:
enum Status implements org.springframework.context.MessageSourceResolvable {
AVAILABLE, SOLD_OUT
public Object[] getArguments() { [] as Object[] }
public String[] getCodes() { [ name() ] }
public String getDefaultMessage() { "?-" + name() }
}
Now we can provide a value in our messages_nl.properties for each enum we have:
product.label=Product
product.name.label=Naam
product.status.label=Status
AVAILABLE=Beschikbaar
SOLD_OUT=Uitverkocht

Observe changes to properties of items in a list in Polymer 1

I have a property
#property final List<Item> items = [
new Item('red', false),
new Item('green', true),
new Item('blue', false)
];
where class Item looks like
class Item extends JsProxy {
#reflectable String color;
#reflectable bool checked;
Item(this.color, this.checked);
}
The HTML looks like
<template is="dom-repeat" items="{{items}}">
<label><span>{{item.color}}</span>
<input type="checkbox"
value="{{item.color}}"
checked="{{item.checked::change}}">
</label>
</template>
I want to be notified when checked in any of the items was changed.
An observer can be set up using the #Observe('some.path') annotation.
If the path contains a .*, the handler is called with a change record which contains the actual path of the change.
#Observe('items.*')
void updateSelectedColors(Map record, [_]) {
String path = record['path'];
if (path == 'items' || path.endsWith('.checked')) {
// do something
}
}
}
path == 'items' applies for the initialization of the items property with the default value. path.endsWidth('.checked') ensures that the code (// do something) is only executed when actually the checked property was changed. All other changes are ignored.

async call to Controller - for state and county

In Grails - I need to make a controller method that will populate State and County dropdown form fields so that when a State is selected it will fill only that State's counties into the County dropdown.
A colleague told me that's an asynchronous call in Grails, but I'm a novice in Grails and I really don't know what that is or how to start one. Any help would be greatly appreciated.
Here's my code snippets:
using Grails 2.43 currently. I have two domain classes (State and County), and two Select dropdowns for State and County.
Form elements:
<g:select name="locationState" class="form-control" from="${....State.list().sort{it.orderNumber}}">
<g:select name="locationCounty" class="form-control" from="${...State.FindByName(it.orderNumber).counties}">
Here are the example classes:
class State {
static hasMany = [county:County]
String name
String value
int orderNumber = 0
static constraints = {
name nullable:false, maxSize:50, blank:false
value nullable:false, maxSize:100, blank:false
}
String toString(){
"$value"
}
static mapping = {
table 'state'
cache: 'read-write'
columns{
id column:'id'
name column:'name'
value column:'value'
orderNumber column:'order_number'
}
id generator: 'assigned'
}
}
class County {
State state
String county
static constraints = {
state nullable:false
county nullable:false, maxSize:100, blank:false
}
String toString(){
"${state.name} - $county"
}
static mapping = {
table 'county'
cache: 'read-write'
columns{
id column:'id'
county column:'county'
state column:'state_id'
}
id generator: 'assigned'
}
}
The async guide linked in the comments is for make programatic, asynchronous calls. For example, if you had two computationally expensive method calls (or ones that would require network I/O) you can use threads to run them (roughly) in parallel. Grails provides many different helpers to make this kind of asynchronous programming very easy.
However, this is not likely something you need for your GORM queries. You want to populate a second select box. You could accomplish this two ways, by reloading the page after the state is selected, or by using JavaScript to populate the box. I am assuming you want to do the latter. Grails does provide tools (such as the <g:remoteFunction /> tag) to handle this without writing your own JavaScript but the Grails AJAX library has since been deprecated and its use is not recommended.
Instead, you should just write your own JavaScript. I'll show you a technique using jQuery:
In your view, initialize both selects, but the second should be initialized as empty. We are also going to give them IDs to make them easier to select from jQuery:
<g:select name="locationState"
class="form-control"
from="${....State.list().sort{it.orderNumber}}"
id="location-state" />
<g:select name="locationCounty"
class="form-control"
from="${[]}"
id="location-county" />
Then, we will need to expose an action on the controller to load the counties when the user selects a state:
def loadCountiesByState() {
def state = params.state
def counties = State.findByValue(state).counties
render g.select(name: 'locationCounty', class: 'form-control',
from: counties, id: 'location-county')
}
You should be able to test this part just by pointing your browser to /app-name/controller-name/loadCountiesByState?state=CA. I don't know exactly how your data is modeled so you might need to alter the State.findByValue(state) part to fit your needs.
Now we just need to wire up the control with some JavaScript. Make sure you have jQuery included.
<script type="text/javascript">
$(function() {
$('#location-sate').change(function() {
var state = $(this).val();
$.ajax({
url: '/app-name/controller-name/loadCountiesByState',
date: { state: state },
success: function(data) {
$('#location-county').replaceWith(data);
}
});
});
});
</script>
This will replace the dropdown with a new select that should be fully populated with the counties.

asp.net mvc validation messages localization for numbers (data-val-number) [duplicate]

Assume this model:
Public Class Detail
...
<DisplayName("Custom DisplayName")>
<Required(ErrorMessage:="Custom ErrorMessage")>
Public Property PercentChange As Integer
...
end class
and the view:
#Html.TextBoxFor(Function(m) m.PercentChange)
will proceed this html:
<input data-val="true"
data-val-number="The field 'Custom DisplayName' must be a number."
data-val-required="Custom ErrorMessage"
id="PercentChange"
name="PercentChange" type="text" value="0" />
I want to customize the data-val-number error message which I guess has generated because PercentChange is an Integer. I was looking for such an attribute to change it, range or whatever related does not work.
I know there is a chance in editing unobtrusive's js file itself or override it in client side. I want to change data-val-number's error message just like others in server side.
You can override the message by supplying the data-val-number attribute yourself when rendering the field. This overrides the default message. This works at least with MVC 4.
#Html.EditorFor(model => model.MyNumberField, new { data_val_number="Supply an integer, dude!" })
Remember that you have to use underscore in the attribute name for Razor to accept your attribute.
What you have to do is:
Add the following code inside Application_Start() in Global.asax:
ClientDataTypeModelValidatorProvider.ResourceClassKey = "Messages";
DefaultModelBinder.ResourceClassKey = "Messages";
Right click your ASP.NET MVC project in VS. Select Add => Add ASP.NET Folder => App_GlobalResources.
Add a .resx file called Messages.resx in that folder.
Add these string resources in the .resx file:
FieldMustBeDate The field {0} must be a date.
FieldMustBeNumeric The field {0} must be a number.
PropertyValueInvalid The value '{0}' is not valid for {1}.
PropertyValueRequired A value is required.
Change the FieldMustBeNumeric value as you want... :)
You're done.
Check this post for more details:
Localizing Default Error Messages in ASP.NET MVC and WebForms
This is not gonna be easy. The default message is stored as an embedded resource into the System.Web.Mvc assembly and the method that is fetching is a private static method of an internal sealed inner class (System.Web.Mvc.ClientDataTypeModelValidatorProvider+NumericModelValidator.MakeErrorString). It's as if the guy at Microsoft coding this was hiding a top secret :-)
You may take a look at the following blog post which describes a possible solution. You basically need to replace the existing ClientDataTypeModelValidatorProvider with a custom one.
If you don't like the hardcore coding that you will need to do you could also replace this integer value inside your view model with a string and have a custom validation attribute on it which would do the parsing and provide a custom error message (which could even be localized).
As an alternate way around this, I applied a RegularExpression attribute to catch the invalid entry and set my message there:
[RegularExpression(#"[0-9]*$", ErrorMessage = "Please enter a valid number ")]
This slightly a hack but this seemed preferable to the complexity the other solutions presented, at least in my particular situation.
EDIT: This worked well in MVC3 but it seems that there may well be better solutions for MVC4+.
From this book on MVC 3 that I have. All you have to do is this:
public class ClientNumberValidatorProvider : ClientDataTypeModelValidatorProvider
{
public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata,
ControllerContext context)
{
bool isNumericField = base.GetValidators(metadata, context).Any();
if (isNumericField)
yield return new ClientSideNumberValidator(metadata, context);
}
}
public class ClientSideNumberValidator : ModelValidator
{
public ClientSideNumberValidator(ModelMetadata metadata,
ControllerContext controllerContext) : base(metadata, controllerContext) { }
public override IEnumerable<ModelValidationResult> Validate(object container)
{
yield break; // Do nothing for server-side validation
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
yield return new ModelClientValidationRule {
ValidationType = "number",
ErrorMessage = string.Format(CultureInfo.CurrentCulture,
ValidationMessages.MustBeNumber,
Metadata.GetDisplayName())
};
}
}
protected void Application_Start()
{
// Leave the rest of this method unchanged
var existingProvider = ModelValidatorProviders.Providers
.Single(x => x is ClientDataTypeModelValidatorProvider);
ModelValidatorProviders.Providers.Remove(existingProvider);
ModelValidatorProviders.Providers.Add(new ClientNumberValidatorProvider());
}
Notice how the ErrorMessage is yielded, you specify the current culture and the localized message is extracted from the ValidationMessages(here be culture specifics).resx resource file. If you don't need that, just replace it with your own message.
Here is another solution which changes the message client side without changed MVC3 source. Full details in this blog post:
https://greenicicle.wordpress.com/2011/02/28/fixing-non-localizable-validation-messages-with-javascript/
In short what you need to do is include the following script after jQuery validation is loaded plus the appropriate localisation file.
(function ($) {
// Walk through the adapters that connect unobstrusive validation to jQuery.validate.
// Look for all adapters that perform number validation
$.each($.validator.unobtrusive.adapters, function () {
if (this.name === "number") {
// Get the method called by the adapter, and replace it with one
// that changes the message to the jQuery.validate default message
// that can be globalized. If that string contains a {0} placeholder,
// it is replaced by the field name.
var baseAdapt = this.adapt;
this.adapt = function (options) {
var fieldName = new RegExp("The field (.+) must be a number").exec(options.message)[1];
options.message = $.validator.format($.validator.messages.number, fieldName);
baseAdapt(options);
};
}
});
} (jQuery));
You can set ResourceKey of ClientDataTypeModelValidatorProvider class to name of a global resource that contains FieldMustBeNumeric key to replace MVC validation error message of number with your custom message. Also key of date validation error message is FieldMustBeDate.
ClientDataTypeModelValidatorProvider.ResourceKey="MyResources"; // MyResource is my global resource
See here for more details on how to add the MyResources.resx file to your project:
Here is another solution in pure js that works if you want to specify messages globally not custom messages for each item.
The key is that validation messages are set using jquery.validation.unobtrusive.js using the data-val-xxx attribute on each element, so all you have to do is to replace those messages before the library uses them, it is a bit dirty but I just wanted to get the work done and fast, so here it goes for number type validation:
$('[data-val-number]').each(function () {
var el = $(this);
var orig = el.data('val-number');
var fieldName = orig.replace('The field ', '');
fieldName = fieldName.replace(' must be a number.', '');
el.attr('data-val-number', fieldName + ' باید عددی باشد')
});
the good thing is that it does not require compiling and you can extend it easily later, not robust though, but fast.
Check this out too:
The Complete Guide To Validation In ASP.NET MVC 3 - Part 2
Main parts of the article follow (copy-pasted).
There are four distinct parts to creating a fully functional custom validator that works on both the client and the server. First we subclass ValidationAttribute and add our server side validation logic. Next we implement IClientValidatable on our attribute to allow HTML5 data-* attributes to be passed to the client. Thirdly, we write a custom JavaScript function that performs validation on the client. Finally, we create an adapter to transform the HTML5 attributes into a format that our custom function can understand. Whilst this sounds like a lot of work, once you get started you will find it relatively straightforward.
Subclassing ValidationAttribute
In this example, we are going to write a NotEqualTo validator that simply checks that the value of one property does not equal the value of another.
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class NotEqualToAttribute : ValidationAttribute
{
private const string DefaultErrorMessage = "{0} cannot be the same as {1}.";
public string OtherProperty { get; private set; }
public NotEqualToAttribute(string otherProperty)
: base(DefaultErrorMessage)
{
if (string.IsNullOrEmpty(otherProperty))
{
throw new ArgumentNullException("otherProperty");
}
OtherProperty = otherProperty;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, OtherProperty);
}
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
if (value != null)
{
var otherProperty = validationContext.ObjectInstance.GetType()
.GetProperty(OtherProperty);
var otherPropertyValue = otherProperty
.GetValue(validationContext.ObjectInstance, null);
if (value.Equals(otherPropertyValue))
{
return new ValidationResult(
FormatErrorMessage(validationContext.DisplayName));
}
}
return ValidationResult.Success;
}
}
Add the new attribute to the password property of the RegisterModel and run the application.
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
[NotEqualTo("UserName")]
public string Password { get; set; }
...
Implementing IClientValidatable
ASP.NET MVC 2 had a mechanism for adding client side validation but it was not very pretty. Thankfully in MVC 3, things have improved and the process is now fairly trivial and thankfully does not involve changing the Global.asax as in the previous version.
The first step is for your custom validation attribute to implement IClientValidatable. This is a simple, one method interface:
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
ModelMetadata metadata,
ControllerContext context)
{
var clientValidationRule = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "notequalto"
};
clientValidationRule.ValidationParameters.Add("otherproperty", OtherProperty);
return new[] { clientValidationRule };
}
If you run the application now and view source, you will see that the password input html now contains your notequalto data attributes:
<div class="editor-field">
<input data-val="true" data-val-notequalto="Password cannot be the same as UserName."
data-val-notequalto-otherproperty="UserName"
data-val-regex="Weak password detected."
data-val-regex-pattern="^(?!password$)(?!12345$).*"
data-val-required="The Password field is required."
id="Password" name="Password" type="password" />
<span class="hint">Enter your password here</span>
<span class="field-validation-valid" data-valmsg-for="Password"
data-valmsg-replace="true"></span>
</div>
Creating a custom jQuery validate function
All of this code is best to be placed in a separate JavaScript file.
(function ($) {
$.validator.addMethod("notequalto", function (value, element, params) {
if (!this.optional(element)) {
var otherProp = $('#' + params);
return (otherProp.val() !=
}
return true;
});
$.validator.unobtrusive.adapters.addSingleVal("notequalto", "otherproperty");
}(jQuery));
Depending on your validation requirements, you may find that the jquery.validate library already has the code that you need for the validation itself. There are lots of validators in jquery.validate that have not been implemented or mapped to data annotations, so if these fulfil your need, then all you need to write in javascript is an adapter or even a call to a built-in adapter which can be as little as a single line. Take a look inside jquery.validate.js to find out what is available.
Using an existing jquery.validate.unobtrusive adapter
The job of the adapter is to read the HTML5 data-* attributes on your form element and convert this data into a form that can be understood by jquery.validate and your custom validation function. You are not required to do all the work yourself though and in many cases, you can call a built-in adapter. jquery.validate.unobtrusive declares three built-in adapters which can be used in the majority of situations. These are:
jQuery.validator.unobtrusive.adapters.addBool - used when your validator does not need any additional data.
jQuery.validator.unobtrusive.adapters.addSingleVal - used when your validator takes in one piece of additional data.
jQuery.validator.unobtrusive.adapters.addMinMax - used when your validator deals with minimum and maximum values such as range or string length.
If your validator does not fit into one of these categories, you are required to write your own adapter using the jQuery.validator.unobtrusive.adapters.add method. This is not as difficulty as it sounds and we'll see an example later in the article.
We use the addSingleVal method, passing in the name of the adapter and the name of the single value that we want to pass. Should the name of the validation function differ from the adapter, you can pass in a third parameter (ruleName):
jQuery.validator.unobtrusive.adapters.addSingleVal("notequalto", "otherproperty", "mynotequaltofunction");
At this point, our custom validator is complete.
For better understanding refer to the article itself which presents more description and a more complex example.
HTH.
I just did this and then used a regex expression:
$(document).ready(function () {
$.validator.methods.number = function (e) {
return true;
};
});
[RegularExpression(#"^[0-9\.]*$", ErrorMessage = "Invalid Amount")]
public decimal? Amount { get; set; }
Or you can simply do this.
#Html.ValidationMessageFor(m => m.PercentChange, "Custom Message: Input value must be a number"), new { #style = "display:none" })
Hope this helps.
I make this putting this on my view
#Html.DropDownListFor(m => m.BenefNamePos, Model.Options, new { onchange = "changePosition(this);", #class="form-control", data_val_number = "This is my custom message" })
I have this problem in KendoGrid, I use a script at the END of View to override data-val-number:
#(Html.Kendo().Grid<Test.ViewModel>(Model)
.Name("listado")
...
.Columns(columns =>
{
columns.Bound("idElementColumn").Filterable(false);
...
}
And at least, in the end of View I put:
<script type="text/javascript">
$("#listado").on("click", function (e) {
$(".k-grid #idElementColumn").attr('data-val-number', 'Ingrese un número.');
});
</script>
a simple method is, use dataanotation change message on ViewModel:
[Required(ErrorMessage ="الزامی")]
[StringLength(maximumLength:50,MinimumLength =2)]
[Display(Name = "نام")]
public string FirstName { get; set; }

Resources