Validate custom constraints with JQuery Validation UI Plugin - grails

I'm using grails JQuery Validation UI Plugin for grails 2.1.0.
I nearly have my form valadting client side based on my command object constraints.
There is one problem, I have a custom constraint in my command object:
startTime(nullable: false, validator: {startTime, deal ->
if ((!DateUtils.isSameDay(startTime, new Date()) && startTime.before(new Date()))) //Start date is today or future but not before end date
{
return "pastDate"
}
if (deal.endTime && startTime.after(deal.endTime)) {
return "before.endTime"
}
})
This results in the following rendered jQuery validation code generated with page markup:
startTime: {
date: true,
required: true,
validator: {
url: '/appContextRoot/JQueryRemoteValidator/validate',
type: 'post',
data: {
validatableClass: 'myapp.command.tester.testerDealCommand',
property: 'startTime'
}
}
}
The custum constrains logic withing "validator:" does nothing currently.
What is the best approach to get this custom validator working?
1: Some form of Ajax call?
2: Use Custom Constraits plugin and add js code to grails-validation-methods.js?
3: Some other way?
I'm unsure of using option 2....is there some way to extend the plugin?
I do not want to have to commit and maintain a seperate version of the plugin in our source code repository.

If I understood correctly the plugin, there's no need to add your custom validations directly to grails-validation-methods.js
If you load your script after, you can just follow his convention:
jQuery.validator.addMethod("myCustomValidation", function(value, element, params) {
//perform your validation here
}, "Custom validation fail.");

Related

Ant Design Dynamic Form Validations

Say I have a dynamic form like this.
How can I validate my users fields to ensure that there is at least one name is filled before user submit the form?
I try to add rules into the Form.List but it is not working.
Adding custom validator to the individual user component only allow me to have access to that particular name component so I can't check the length of the name array.
Manage to make it works by adding this to the rules:
({ getFieldValue }) => ({
validator() {
if (getFieldValue("users").length > 1) {
return Promise.resolve();
}
return Promise.reject(
"Please add at least 2 options"
);
}
})
Check here

ASP.NET MVC Partial View in an AngularJS directive

I'm currently working on an ASP.NET MVC project to which some AngularJS was added - including some AngularJS directives.
I need to add to an AngularJS directive a MVC partial view. Obviously,
#Html.Partial("_PartialView", {{name}})
doesn't work.
So far all my searches online provided no help.
Any idea how I could render a partial view inside an Angular directive?
Thanks!
Angular exists strictly on the client side whereas MVC views exist on the server side. These two cannot interact directly. However, you could create an endpoint in which your partial view is returned as HTML. Angular could call this endpoint, retrieve the HTML, and then include it inside a directive.
Something like this:
app.directive("specialView", function($http) {
return {
link: function(scope, element) {
$http.get("/views/partials/special-view") // immediately call to retrieve partial
.success(function(data) {
element.html(data); // replace insides of this element with response
});
}
};
});
app.directive("myDirective", ['', function () {
return {
restrict: 'A',
scope: {
foo: '='
},
templateUrl: '/home/_myDirectivePartialView',
}]
} }]);
Just need to use templareURL and specify the route to get the partial view.

grails 2.1.1 command object service injection for custom validator

Grails 2.1.1
I can't seem to get a command object to be injected with a service so that I can use custom validator. I've tried several things, including
Grails command object data binding and
what the 2.1.1 docs on custom validator suggest, I just can't figure this one out..
Relevant Code:
class RegistrationCommand {
String username
def registrationService
static constraints = {
username validator: { val, obj ->
obj.registrationService.isUsernameUnique(val) }
}
}
class RegistrationService {
def isUsernameUnique(username){
def user = new User(username:username)
user.validate()
if(user.errors.hasFieldErrors("username")){
return false
}else{
return true
}
}
Resolved.. Issue was due to plugin.
I'm using a plugin for client side jquery validation (jquery-validation-ui-1.4.2). The command object being created by the plugin's controller wasn't getting injected with the service. The issue was reported https://github.com/limcheekin/jquery-validation-ui/issues/17 . The fix does work but has not been pushed upstream yet.

Invoking action method using Java script in asp.net MVC

I have a form, I want to check the username is availability. I that I have html textbox, in Onclcik I'm calling java script function. The script has to call the Action methods in controller. Based upon the username availability it has to return either 1 or 0. I have tried Json. But its is showing "Microsoft JScript runtime error: '$' is undefined". Can anyone help me in this.
If you get that message it means you're trying to use jQuery but you haven't included the library. You can use Google's CDN.
I guess you've used Ajax to call. Something like this:
$.ajax({
type: 'POST',
url: '<%=Url.Action("Your Action", "Your Controller")%>',
data: { userName: $('#UserName').val(), password: $('#Password').val() },
dataType: 'json',
complete: function(XMLHttpRequest, textStatus) {
// User your JSON response.
}
});
If you're using a POST you have to decorate your action with the attribute [HttpPost]
and remember to specify JsonRequestBehavior.DenyGet when you return your JSON object:
[HttpPost]
public JsonResult CheckUserName(string userName, string password)
{
// notification: your object
return (Json(notification, JsonRequestBehavior.DenyGet));
}
If you are using Jquery (the $ sign), then that means that you need a script reference to jquery implementation before your javascript code that calls JSON.
script type="text/javascript" src="jquery.js"></script>
Where jquery.js is the latest version of the jquery javascript file

Prevent user from submitting if a field is not unique in an MVC form using AJAX

You know those fields you see on forms which indicate that a value can't be used because its already used? Like a username for a membership site.
I'd like to do this for an MVC form via jquery. What is the recommendation for this?
You could create a JsonResult action that you can call from your javascript code. Eg
public JsonResult IsUsernameAvailable(string username) {
// return result
return Json(true);
}
And then hook it up to your username-field like so using jQuery
$("#username").blur(function() { checkAvailability($(this).val()); });
function checkAvailability(username) {
$.getJSON("/User/IsUsernameAvailable", { username: username }, function(result) {
alert("Is available: " + result);
});
}
If you are using MVC 3 there is a new Remote attribute which you can use. You specify a route or controller/action for the attribute and return "true" or "false" (or any string != "true", which could be 'result' in your case. You will get a client side validation error similar to the errors you get if a required field is left blank etc.

Resources