After having read this page I found a way of internationalizing validation messages. It is done by placing translations of each error type into ValidationMessages.properties files.
javax.validation.constraints.Size.message=The property must be between {min} and {max}
javax.validation.constraints.NotNull.message=The property must not be null
It is error type-specific and it's not what I need in my app. I need a unique message for each of my fields in validated beans. With no internationalization it can be done using annotations.
#Pattern(regexp = UiLogicUtils.EMAIL_REGEX, message = "Email is invalid.")
private String requesterEmail;
So how can I make translations of the "Email is invalid" text just for this specific field?
I don't know if this is the answer, because I have not used #Pattern, but in the docs, it says that the message field of the #Pattern is not a text, but a key into the messages file. Look here:
http://docs.oracle.com/javaee/6/api/javax/validation/constraints/Pattern.html#message()
By default message="{javax.validation.constraints.Pattern.message}" which looks like a valid key in ValidationMessages.properties file. I suppose you only have to specify a custom key and use it.
Related
I am using the Play framework in Scala to develop a small blog website. I currently have a form (successfully) set up for an easy registration of users. This login page just accepts a username (ie. no password yet), verifies that is of the appropriate length and doesn't exist yet, and adds this user to the database (currently still in memory). Length can be verified using just the basic form functionality, however, the uniqueness of this username required me to use custom validations.
Now, this all works, except for the custom error message. When a normal form requirement is not fulfilled, an error message is returned and displayed in the view (eg. "The minimum length is: 5"). I want to display a similar message when the name is not unique. In the first link I provided there is an example of custom validations which seems to have an argument that represents such custom error message for validations you write of your own. However, this does not display in the view, while the others do.
Current validation code:
private val myForm: Form[Account] =
Form(mapping("name" -> text(3, 24))(Account.apply)(Account.unapply).verifying(
"Account is not in the DB.",
fields =>
fields match {
case data: Account => accountExists(data.name).isDefined
}
)
)
Anyone has any ideas?
I am currently programming a REST service and a website that mostly uses this REST service.
Model:
public class User {
private String realname;
private String username;
private String emailAddress;
private String password;
private Role role;
..
}
View:
One form to update
realname
email address
username
Another form to update the role
And a third form to change the password
.
Focussing on the first view, which pattern would be a good practice?
PUT /user/{userId}
imho not because the form contains only partial data (not role, not password). So it cannot send a whole user object.
PATCH /user/{userId}
may be ok. Is a good way to implement it like:
1) read current user entity
2)
if(source.getRealname() != null) // Check if field was set (partial update)
dest.setRealname(source.getRealname());
.. for all available fields
3) save dest
POST /user/{userId}/generalInformation
as summary for realname, email, username
.
Thank you!
One problem with this approach is that user cannot nullify optional fields since code is not applying the value if (input is empty and value) is null.
This might be ok for password or other required entity field but for example if you have an optional Note field then the user cannot "clean" the field.
Also, if you are using a plain FORM you cannot use PATCH method, only GET or POST.
If you are using Ajax you might be interested in JSON Merge Patch (easier) and/or JavaScript Object Notation (JSON) Patch (most complete); for an overview of the problems that one can find in partial updates and in using PATCH see also this page.
A point is that a form can only send empty or filled value, while a JSON object property can have three states: value (update), null (set null) and no-property (ignore).
An implementation I used with success is ZJSONPATCH
Focussing on the first view, which pattern would be a good practice?
My suggestion starts from a simple idea: how would you do this as web pages in HTML?
You probably start from a page that offers a view of the user, with hyperlinks like "Update profile", "Update role", "Change password". Clicking on update profile would load an html form, maybe with a bunch of default values already filled in. The operator would make changes, then submit the form, which would send a message to an endpoint that knows how to decode the message body and update the model.
The first two steps are "safe" -- the operator isn't proposing any changes. In the last step, the operator is proposing a change, so safe methods would not be appropriate.
HTML, as a hypermedia format, is limited to two methods (GET, POST), so we might see the browser do something like
GET /user/:id
GET /forms/updateGeneralInformation?:id
POST /updates/generalInformation/:id
There are lots of different spellings you can use, depending on how to prefer to organize your resources. The browser doesn't care, because it's just following links.
You have that same flexibility in your API. The first trick in the kit should always be "can I solve this with a new resource?".
Ian S Robinson observed: specialization and innovation depend on an open set. If you restrict yourself to a closed vocabulary of HTTP methods, then the open set you need to innovate needs to lie elsewhere: the RESTful approach is to use an open set of resources.
Update of a profile really does sound like an operation that should be idempotent, so you'd like to use PUT if you can. Is there anything wrong with:
GET /user/:id/generalInformation
PUT /user/:id/generalInformation
It's a write, it's idempotent, it's a complete replacement of the generalInformation resource, so the HTTP spec is happy.
Yes, changing the current representation of multiple resources with a single request is valid HTTP. In fact, this is one of the approaches described by RFC 7231
Partial content updates are possible by targeting a separately identified resource with state that overlaps a portion of the larger resource
If you don't like supporting multiple views of a resource and supporting PUT on each, you can apply the same heuristic ("add more resources") by introducing a command queue to handle changes to the underlying model.
GET /user/:id/generalInformation
PUT /changeRequests/:uuid
Up to you whether you want to represent all change requests as entries in the same collection, or having specialized collections of change requests for subsets of operations. Tomato, tomahto.
I am using DateTextField for edit date field,
if user enter invalid date (eg. enter any character inseated of date)
then in on submit form DateTextField internally create invalid date message based on id.
My code is :
form.add(DateTextField.forDatePattern("orderStartDate", new DateModel(new PropertyModel<Date>(this, "defaultModelObject.startDate")), "dd/MM/yyyy"));
Now if a user enters any invalid date then in form submit, DateTextField generates the message.
"The value of 'orderStartDate' is not a valid Date."
In message 'orderStartDate' is id which i set on DateTextField;
Now I want to create custom message for this error inseated of above message;
The default value comes from IConverter resource bundle key: https://github.com/apache/wicket/blob/77b4df63f44d00e9350068686e4b091f730f167f/wicket-core/src/main/java/org/apache/wicket/Application.properties#L16
You need to provide a more specific one in YourApplication.properties to override it, e.g.:
orderStartDate.IConverter=Please provide a date with pattern dd/MM/yyyy.
The Validators usually report their class into the Error object. When Wicket generates the FeedbackMessage, it looks it up in the StringResourceModel. So if you use .properties or .properties.xml files for wording, you might want to add the FeedbackMessage using the key of IConverter (which reported the error)
<entry key="IConverter.Date">Please use the format dd/MM/yyyy!</entry>
Same story for required FormComponents
<entry key="Required">Please provide a value!</entry>
If you some day write your own validator, give it a key and optional parameters.
private void error(IValidatable<String> validatable) {
ValidationError error = new ValidationError();
error.addKey("id.exists");
error.setVariable("id", valueThatIsNotValid); // variable held in class
ekpCmp.error(error);
}
and define the StringResource
<entry key="id.exists">The value ${id} already exists.</entry>
I'm dealing with a Webflow application where I may have to submit the current form in order to delete a child record (complex workflow, sorry).
The problem is that if the user enters junk data into the form and then presses the "delete" button, the binding and/or validation will fail and the form will never be submitted.
Hence, if they enter junk data, they cannot delete the record.
What is the preferred way of dealing with users entering "junk" data in web forms, particularly entering non-numeric data in numeric fields? I have a Spring form backing object that looks like this:
public class MyFormInfo implements Serializable {
private String myName;
private Integer myNumber;
}
If the user enters junk in the myName field I can ignore that during validation. However if they enter junk in the myNumber field and the binding fails, I have no good way to trap that and I can't submit the form.
Anybody have a good way to deal with this?
Have a look at this answer as well, but in summary there is no good way to add an error message in the case of type mismatch at conversion time.
The mechanisms available (property editors, converters, bean validation) are not meant to deal with a type mismatch.
The best solution is probably to do the validation on the client side via Javascript via some field mask that only accepts numerics. Then on the server a type mismatch would only occur in case of a bug, so the unhandled error could be acceptable.
For doing this on the server, it's possible to add a String property to the DTO, and apply a bean validation:
#Pattern(regexp = "{A-Za-z0-9}*")
String numericField;
Then via bean validation is possible to add error messages to the page, see this example.
If you want to avoid decimal number input in Integer fields, you can do it like this:
In the HTML-form you can do:
<div class="form-outline">
<input type="number" min=1 max=100 required/>
</div>
In the Java-Form you can do:
#NotNull
#Max(value = 100)
#Min(value = 1)
#NumberFormat
private Integer countOfRooms = null;
I am validating an email address using zend_validate_email.
For example, for email address aa#aa it throws several error messages including very technical describing that DNS mismatch (:S).
I am trying to make it display only 1 message that I want it to (for example: "Please enter a valid email").
Is there any way of doing it elegantly, apart from creating a subclass and overriding the isValid method, clearing out the array of error messages?
Thanks!
$validator = new Zend_Validate_EmailAddress();
// sets the message for all error types
$validator->setMessage('Please enter a valid email');
// sets the message for the INVALID_SEGMENT error
$validator->setMessage('Something with the part after the # is wrong', Zend_Validate_EmailAddress::INVALID_SEGMENT);
For a full list of errors and message templates see the Zend_Validate_EmailAddress class