I have some custom validation that I need to perform that involves checking the selected option of a dropdown and flagging it as invalid should the user select a specific option.
I am using ASP.NET MVC 2 and have a custom Validator and custom server side and client side validation rules as described in this blog article. The server side validation is working fine, however, the client side validation is failing.
Here is the javascript validation rule:
Sys.Mvc.ValidatorRegistry.validators["badValue"] = function(rule) {
var badValue = rule.ValidationParameters["badValue"];
return function(value, context) {
if (value != badValue) {
return true;
}
return rule.ErrorMessage;
};
};
The rule is being applied to the dropdowns successfully, and placing a breakpoint within the returned function confirms that the validation is firing, and that the 'badValue' is being correctly set. However, 'value' is always null, and so the check always fails. What am I doing wrong?
Related
I am working in a project using JPA, and Bean Validation. I want to show friendly messages to the user about the validations that failed, and I need to show these messages in different languages based on the Locale of the users.
I am using standard annotations like #NotNull, #Size, as well as some custom class level validations.
I am using the following code to validate the entities before persist them:
Validator validator = validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Company>> constraintViolations = validator.validate(company);
if (constraintViolations.size() > 0) {
Set<String> violationMessages = new HashSet<String>();
for (ConstraintViolation<Company> constraintViolation : constraintViolations) {
violationMessages.add(constraintViolation.getPropertyPath() + ": " + constraintViolation.getMessage());
}
}
If validation failed I can see the messages and the fields that failed validation, but I don't know how to convert these validation messages to friendly ones and in different languages (based on the Locale of the users).
I have the following questions:
What is the proper way to achieve this?
I know that JPA checks automatically the entities against validations before persist. If I execute the validation manually (with the above code) am I running the validation process twice?
If I am using JSF which also executes validations before update the model, I am running the validation process three times (1. JSF, 2. the above code and 3. Wildfly/JPA before persist/merge)?
If the above code runs in an EJB, how can I pass the validation errors to the presentation layer (JSF for example)?
Do I need to return a list of ConstraintViolations to the presentation layer? - Do I need to create an exception for each validation?
Thank you
When submitting a form to my backend, I might get a response with http code 400 indicating that validation has failed.
My backend responds with for example:
{
"status":"fail",
"data":{
"email":[
"Email address already in use"
]
}
}
I would like to invalidate the email field and set the error message, based on the response.
What I've tried is this:
if (err && err.status === 400) {
const response = err.json();
Object.keys(response.data).forEach(key => {
const messages = response.data[key];
this.registerForm.get(key).setErrors({
remote: messages[0] // Set just the first message
}, true);
});
}
This seems to work in part, the problem is that my controls does not get invalid status unless I focus the control by clicking the input.
Am I doing something wrong or is it a bug? All my Googling seems to confirm that I'm doing it correctly.
Any input appr
You can re-implement the register form adapting the reactive form style, where you can perform custom validation of form inputs and do asynchronous validation by returning promises to form to update on resolving the promise.
You may check in Angular 2 documentation for implementing reactive form validation : Reactive Form Validation - Angular 2
I'm currently trying to connect an Extjs form to a Play! Scala backend.
I have no problem receiving the request, but
FormName.bindFromRequest.get returns to me None .
I'm able to find the data generated via submitting from Extjs in the POST request in request.request.body.data (the first request object is generated by SocialSecure's controller), whereas normally the data bound to the form would be found in request.request.body.data.elems
I think Extjs's eschewal of using <form> in their inserted HTML is what causes me this problem, but I'd still like to take advantage of Extjs's nice form verification UI.
Does Play! or Scala have any resources for modifying a request after the server has received it?
More info
This is the method my /requestAudit cuurently points to after a POST request:
def requestAudit = SecuredAction(WithProvider("google")) { // SecureSocial syntax
implicit request => { // let's call this line 0'
println(request.request.body.asFormUrlEncoded) // let's call this line 1'
println(request.body.asText) // let's call this line 2'
newAuditForm.bindFromRequest.fold(
errors => BadRequest(views.html.error(newAuditForm))
success => { /*insert the object into my db*/ }
) } }
Ext.js request
When I'm debugging in Eclipse with an Ext.js form, the Variables window shows: (click for closeup)
where the form values are located in request.body.data.key1, request.body.data.key2, etc
Bootstrap form request
On the other hand, the request for Bootstrap has the values stored in request.body.data.elems
#2manyprojects 's suggestion set me on the right path:
newAuditForm.bindFromRequest(
(request.request.body.asFormUrlEncoded).getOrElse(Map()))
.fold( ... )
worked.
I was still getting form binding errors after changing my code to this, and then I discovered a typo in the name property of one of my Ext.js form fields. The name of the field must be the same on both the UI and the Play Form.
We have a number of forms on our site that are shown with jquery .dialog and we submit them using an ajax post request.
I've done a fair bit of research and from what I can tell there isn't any definite patterns on how to return validation errors from the server side as a result of an ajax request.
Pretty much the only pattern I could find was to post the form and then do validation server side and in either case return a json object that encapsulated a result and if the result was incorrect the form html
ie.
{result: true}
{success: false, html = "<form>....</form>"}
So in the case the result was false you would need to rewire up any events attached to items on the form as you would be replacing the old form with the new form that has the validation errors.
This seems like an ok approach but you also end up potentially returning a lot more data to the client that you need to when they only really need to validation messages and you are also forced to rewire the form up which is a bit annoying.
I did find one other mention of somehow getting the validation errors and returning them in a json object from the action and somehow telling the client to display them against the correct fields.
Is there any frameworks out there that make this easier or should I write my own or just stick to returning the entire partial for the form and rewiring it when validation is incorrect?
I don't know of any frameworks that handle this particular case–and I don't know that there's a clear best practice–but it's easy enough to serialize validation errors and return them as a JSON object. You could try this extension method on ModelStateDictionary:
public static IEnumerable<ValidationResult> GetValidationResults(this ModelStateDictionary dictionary)
{
foreach (var key in dictionary.Keys)
foreach (var error in dictionary[key].Errors)
if (error != null)
yield return new ValidationResult(error.ErrorMessage, new string[] { key });
}
And in the controller:
if (!ModelState.IsValid)
{
return new JsonResult(ModelState.GetValidationResults());
}
But you're right, you would then have to loop through the object and append the errors to the correct fields. If you have ClientValidationEnabled and UnobtrusiveJavaScriptEnabled set to true, the loop would look something like this:
$.each(errors, function(i, item) {
$('span[data-valmsg-for=' + item.MemberNames[0] + ']').html(item.ErrorMessage);
})
If not, it wouldn't be that difficult to match up the error messages to their respective fields as the object contains the field name. This would definitely save you some data across the wire, but it moves a larger share of the validation responsibility into Javascript. Like I said, I don't know that there's a clear best practice, but I have used this method in the past with success.
I'm wondering if anyone can assist me in updating the code detailed here (http://oif.eafarris.com/blog/pre-fill-cck-node-fields-based-on-a-node-re...) for Drupal 7. The function described in that post is identical to what I'm looking to do on my Drupal 7 site but I'm not well versed enough programmatically to do it myself.
I have a content type Event. On the node creation form for Event, I have an autocomplete field for "Client". Below that are additional fields for name, address, etc. The end result I'm hoping to achieve here is:
User enters client name in the autocomplete Client field.
Entered client name matches an existing client and is selected.
Using the node ID of the selected client, the address fields are then populated automatically.
I have a JSON view with a nid argument which spits out the required fields at the url http://domain.com/json-clients/[nid]. But I am unable to get that info returned to the correct fields on the form.
Below is the code as I've got it modified trying to get it to work with D7. Anyone see the glaring errors and care to assist?
(function ($) {
Drupal.behaviors.sponsorhelper = function () {
$("input[name='field_client[und][0][nid]']").blur(function() {
nidRegEx = /\[nid:(\d+)\]/;
SponsorHelper.fill($(this).attr('value').match(nidRegEx)[1]);
})
};
SponsorHelper.fill = function(nid) {
var url = Drupal.settings.basePath + 'json-clients/' + nid;
jQuery.getJSON(url, function (data, result) {
if (result != 'success') {
return;
}
$("input[name='field_address_1[und][0][value]']")
.attr('value',data.nodes[0].node.field_address_1_value);
$("input[name='field_address_2[und][0][value]']")
.attr('value',data.nodes[0].node.field_address_2_value);
})
};
})(jQuery);
Any help is greatly appreciated.
Thanks.
Instead of writing your own javascript try handling this with a couple of drupal's community modules. Check out:
http://drupal.org/project/conditional_fields
http://drupal.org/project/computed_field/
You can us conditional fields to hide the address until the client info is put in. Then use computed fields to search for the client and auto fill the address fields.