async call to Controller - for state and county - grails

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.

Related

How do you iterate through a String which is an attribute from an object in Struts2? [duplicate]

I have a edit page in which I want to retrieve the subjects and levels from database and display as select option for user to edit the course.
When the form is submitted, it will make a new request , the user input is captured by courseBean with XML validation. When the XML validation failed, it will forward with the courseBean which just captured the user input to the edit.jsp.
So every time I go the edit.jsp, I will retrieve the database records. Should I do it in that way?
Besides, I tried to retrieve the subject lit and level lit and store them as the request attribute in the action class which displays edit.jsp at the first time. But when the new request is made from the user input, the subject list and level list retrieved from the database will be no longer available.
codes (edit.jsp) :
<%
Session session2 = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session2.beginTransaction();
Query q = session2.createQuery("from Subject");
List subjectList = q.list();
List levelList = session2.createQuery("from Level").list();
%>
<div class="control-group">
<label class="control-label" for="inputPassword">Subject</label>
<div class="controls">
<select name="subject_id">
<%
for (Object subjectObject : subjectList) {
Subject subject = (Subject) subjectObject;
%>
<option value="<%=subject.getId()%>"><%=subject.getName()%></option>
<% } //end for %>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Level</label>
<div class="controls">
<select name="level_id">
<%
for (Object levelObject : levelList) {
Level level = (Level) levelObject;
%>
<option value="<%=level.getId()%>"><%=level.getName()%></option>
<% } //end for %>
</select>
</div>
</div>
Using Struts2 you won't need to use Scriptlets (<% stuff %>) anymore. They're old, bad, they're business logic injected in view pages, do not use them. You do not need JSTL neither, just using Struts2 tags you can achieve any result.
For a better decoupling and separation of code and concepts, you should have:
DAO Layer: it does just the plain queries;
BUSINESS Layer: it exposes the DAO Layer results through Service(s), aggregating multiple DAOs calls and performing several business operations when needed;
PRESENTATION Layer: The Actions, that in Struts2 acts as the Model; here you call the Service from the Business Layer, to retrieve the objects needed by the JSP;
JSP (VIEW Layer): the JSP contains the plain HTML, and accesses the data needed through the Accessors (Getters) of the Action, and eventually any other needed element from the Value Stack (#session, #request, etc).
In your example, all of this
<%
Session session2 = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session2.beginTransaction();
Query q = session2.createQuery("from Subject");
List subjectList = q.list();
List levelList = session2.createQuery("from Level").list();
%>
should be in DAO/Business Layers, exposed by two function like getSubjectList(); and getLevelList();. Then in your Action you should have something like:
public class YourAction {
private List<Object> levelList; // private
private List<Object> subjectList; // private
public String execute() throws Exception {
// Call the service, load data
levelList = getMyService().getLevelList();
subjectList = getMyService().getSubjectList();
// Forwarding to the JSP
return SUCCESS;
}
public List<Object> getLevelList() {
return levelList;
}
public List<Object> getSubjectList() {
return subjectList;
}
}
and in your JSP, instead of:
<select name="subject_id">
<%
for (Object subjectObject : subjectList) {
subject subject = (Subject) subjectObject;
%>
<option value="<%=subject.getId()%>"><%=subject.getName()%></option>
<%
} //end for
%>
</select>
you access the list like (ugly mixed HTML/Struts2 way):
<select name="subject_id">
<s:iterator value="subjectList">
<option value="<s:property value="id"/>">
<s:property value="name"/>
</option>
</s:iterator>
</select>
or, in the case of a Select, with the proper Struts2 UI Select Tag:
<s:select name = "subject_id"
list = "subjectList"
listKey = "id"
listValue = "name" />
If separating all the layers is too difficult at the beginning, flatten the first three levels in the Actions, just to understand how to separata Java (Action) and Struts2 UI Tags (JSP).
When understood, you can move the DAO logic to the business layer, preferably into an EJB. When achieved that, split again with more granularity...
The Action will be something LIKE this:
public class YourAction {
private List<Object> levelList; // private
private List<Object> subjectList; // private
public String execute() throws Exception {
Session session2 = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session2.beginTransaction();
Query q = session2.createQuery("from Subject");
subjectList = q.list();
levelList = session2.createQuery("from Level").list();
// Forwarding to the JSP
return SUCCESS;
}
public List<Object> getLevelList() {
return levelList;
}
public List<Object> getSubjectList() {
return subjectList;
}
}
About your question on multiple loading of the lists, you can use a cache (better if with a timer) if the list is fixed (it changes one a month for example), or loading it every time, there aren't problems in doing that.
Please note that if validation fails, the ValidationInterceptor will forward the request to the JSP mapped in the INPUT type result, without reaching the execute() method, so you should implement Preparable interface from Action and put the loading stuff into prepare() method, execute every time by the PrepareInterceptor
public class YourAction implements Preparable {
private List<Object> levelList; // private
private List<Object> subjectList; // private
public void prepare() throws Exception {
// Call the service, load data,
// every time even if validation fails
levelList = getMyService().getLevelList();
subjectList = getMyService().getSubjectList();
}
public String execute() throws Exception {
// Forwarding to the JSP
return SUCCESS;
}
public List<Object> getLevelList() {
return levelList;
}
public List<Object> getSubjectList() {
return subjectList;
}
}
Proceed by steps, the framework is easy and powerful, the web has plenty of examples and StackOverflow provides some great support...
What you need is a cache. But if the database records are bound to change frequently it's inadvisable.
If however the Query in question is small (I think it is) querying the database shouldn't be a big performance problem.
On another note, looking at your JSP all I see is deprecated and misuse of JSP scriplets.
Since you have added the tag struts 2 I will assume that this is a struts 2 web project. Consider (strongly) using built in struts ui tags for the work done in you scriplets.
Your approach can only be described as using a bunch of dynamos to power a city when you have a nuclear reactor at your disposal.
I suggest you start here : http://struts.apache.org/2.x/docs/home.html
This will give you a proper idea of the framework and it's full capabilities.
One advice, if you want to stick to MVC architecture then never have Business Logic in View. According to MVC architecture the UI Engineers who work with View need not not to know about the Business Logic at all.
Intermixing HTML and Java Code in your JSP page complicates the View and will cause problems in maintaining the code.
Make use of this tutorial to see how to implement CRUD operations in Struts 2.

GORM: how to retrieve only two values for dropdown

In Grails using GORM, I'd like to retrieve two possible values for a form dropdown. This particular instance is to only have two possible countries in a dropdown. I've set them in my Config.groovy
The GORM statement in this that I've done only returns USA and I'd like to return Canada also - so I have the findAll statement slightly incorrect. Can someone help me?
Country<g:select name="Country" from="${....country.findAllById("100225","100038").sort{it.orderNumber}}" value="otherstuff" class="form-control" required="" aria-labelledby="country-label"/>
Config.groovy:
country.usa=100225
country.canada=100038
Domain class:
class country {
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(){
"$name - $value"
}
static mapping = {
table 'country'
cache: 'read-write'
columns{
id column:'id'
name column:'name'
value column:'value'
orderNumber column:'order_number'
}
id generator: 'assigned'
}
}
you should rather use findAllByIdInList(["100225","100038"]).
Also consider not writing such code within the view. Make it part of your model and prepare it in the controller.

Grails: tags that supports data binding?

Are there any tags that support databinding other than select? . I use it for one to many relationships
It seems impractical if you have lots of data and scrolling will be longer
It would be awesome if its just a list of checkboxes then there will be a pagination
g.select is just Grails default, but you can customize the view and use any element, since the information is there. Example:
class Parent {
String name
static hasMany = [childrens: Child]
}
class Child {
String name
}
class ParentController {
def create() {
Parent parentInstance = new Parent()
List<Children> childrens = Children.list()
[parentInstance : parentInstance, childrens: childrens]
}
def save() {
def childrens = params.list('childrens')
println childrens //will output all checkbox marked...
}
}
form.gsp
<ul>
<g:each in="${childrens}" var="child">
<li><g:checkBox name="childrens" value="${child in parentInstance.childrens}" /></li>
</g:each>
</ul>
Some key points here:
You may reconsider this approach if your hasMany side can have a lot of records;
All your checkboxes must have the same name to be considered as a list;
When updating the Parent you need to delete the relations before adding the new ones;
Related topic: Grails - Simple hasMany Problem - Using CheckBoxes rather than HTML Select in create.gsp

Where can i find an example of jqGrid being used as part of form for posting?

I have a form where I have a bunch of textbox and dropdowns. I now need to add another array of sub objects and include that as part of the my form post.
I was going to hand roll this as an html table but i thought that i could leverage jqGrid. What is the best way I can use jqGrid locally to add data and then have that included in the form post? The reason that i need jqGrid to act locally is that these are subrecords as part of the larger form so I can't post the jqGrid rows until the larger form is posted (so i have an Id to join these rows with)
So for example, if my post was an Order screen (with textboxes for date, instructions, etc) and now i want to have a grid that you can add products into the order. You can have as many rows as you want . .)
my backend is asp.net-mvc if that helps with any suggestions.
If you use form editing you can extend the postdata in many ways. The most simple one is the usage of onclickSubmit callback:
onclickSubmit: function (options, postData) {
return {foo: "bar"};
}
If you use the above callback then the data which will be post to the server will be extended with the parameter foo with the string value "bar".
Another possibility is the usage of editData option of editGridRow. The best way is to use properties of editData defined as function. In the way the funcion will be called every time before posting of data.
For example the following code
$("#grid").jqGrid("navGrid", "#pager", {}, {
editData: {
foo: function () {
return "bar";
}
},
onclickSubmit: function (options, postData) {
return {test: 123};
}
});
will add foo=bar and test=123 to the parameters which will be send to the server.
The next possibility will be to use serializeEditData. The callback gives you full control on the data which will be sent to the server.
I am using the method of serialization as Oleg suggested.
view
$( "#Save" ).click( function ( e )
{
e.preventDefault();
var griddata= $( "#list" ).getRowData();
var model = {
grid: griddata
};
var gridVal = JSON.stringify( model );
//Now set this value to a hiddenfield in the form and submit
$('#hiddenGridDta').val(gridVal );
$( 'form' ).submit();
});
And in the controller, deserialize the values using Newtonsoft.json.jsonconvert().
public ActionResult SaveTest(TestClass test)
{
testViewModel myGrid = JsonConvert.DeserializeObject<testViewModel>(test.hiddenGridDta);
................
}
testViewModel class
public class testViewModel
{
public IEnumerable<TestGrid> grid { get; set; }
}
TestGrid class
public class profileGrid
{
//fields in the jqgrid (should use the same name as used in *colModel:* of jqgrid)
public int x
{
get;
set;
}
public int y
{
get;
set;
}
.......
}

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