I have two Date customer components in XPages, One called startDate, another called EndDate. I have already got working validator method in Java for format validation. I want to do the Time range validation in Java code rather than xp:validateDateTimeRange.
Is it possible?When should be happened?It's in validation scope or later scope.
Thanks
To fit into the XPages & JSF validators and converters model, you would put your java code for format validation into a converter, and after doing the format validation, it should convert the submitted String to a java.util.Date. If the converter fails it should add a FacesMessage with the error message (there are blog posts with details - search FacesMessage).
[FYI, for date conversion there are many subtle gotchas around different date formats used in different countries, and around behavior when the browser and the server are in different timezones, and around handling daylight savings time in the different timezones.]
The converted Date object would then be made available to the validator (instead of the original string).
You can use a xp:validateExpression to call your Java date range validation. If you return false from the xp:validateExpression expression, it will use the error text provided in the message property. Else if you want to use different error messages use the FacesMessage mechanism instead of returning false.
Here's an example of a custom date date range converter:
<xp:validateExpression
message="The end date must be after the start date.">
<xp:this.expression><![CDATA[#{javascript:// Server-side validation.
// value is the end date java.util.Date object
var startDate = getComponent('inputText1').getValue();
if( null == startDate ){
// no start date - this error message not applicable, validation pass.
return true;
}
if( value.before(startDate) ){
// failed validation
return false;
}
return true;}]]></xp:this.expression>
<xp:this.clientScript><![CDATA[// client-side validation (browser JavaScript)
function validate(){
var startDate = dijit.byId('#{id:inputText1}').get('value');
var endDate = dijit.byId('#{id:inputText2}').get('value');
if( null == startDate || null == endDate){
return true; // this error message not applicable, passed.
}
if( endDate.getTime() < startDate.getTime() ){
return false; // failed validation
}
return true;
}
validate()
]]></xp:this.clientScript>
</xp:validateExpression>
</xp:this.validators>
Related
How to do some date validation here so that when user enter end date less than start date it will prompt error to user? Is there any built in function made by AppMaker? Thanks for sharing!
If you want to limit the input to a data model, you can use the Advanced section of the data model.
You can also achieve data validation through Event section or Data Validation section. Use the the first one to implement small scripts and the second one to hardcode rules into the app.
// date is not a previous date
var date = new Date();
if (widget.value < date) {
alert('Invalid date');
}
// date is not a future date
var date = new Date();
if (widget.value > date) {
alert('Invalid date');
}
// second date is not higher than first date
if (widget.value > widget.parent.descendants.firstDate.value) {
alert('Invalid date');
}
I have a problem with a p:selectOneMenu, no matter what I do I cannot get JSF to call the setter on the JPA entity. JSF validation fails with this message:
form:location: Validation Error: Value is not valid
I have this working on several other class of the same type (ie, join table classes) but cannot for the life of me get this one working.
If anyone can throw some troubleshooting/debugging tips for this sort of problem it would be greatly appreciated.
Using log statements I have verified the following:
The Conveter is returning correct, non null values.
I have no Bean Validation in my JPA entities.
The setter setLocation(Location location) is never called.
This is the simplest example I can do and it simply will not work:
<h:body>
<h:form id="form">
<p:messages id="messages" autoUpdate="true" />
<p:selectOneMenu id="location" value="#{locationStockList.selected.location}" converter="locationConverter">
<p:ajax event="change" update=":form:lblLocation"/>
<f:selectItems value="#{locationStockList.locationSelection}"/>
</p:selectOneMenu>
</h:form>
</h:body>
Converter:
#FacesConverter(forClass=Location.class, value="locationConverter")
public class LocationConverter implements Converter, Serializable {
private static final Logger logger = Logger.getLogger(LocationConverter.class.getName());
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value.isEmpty())
return null;
try {
Long id = Long.parseLong(value);
Location location = ((LocationManagedBean) context.getApplication().getELResolver().getValue(context.getELContext(), null, "location")).find(id);
logger.log(Level.SEVERE, "Converted {0} to {1}" , new Object[] {value, location});
return location;
} catch (NumberFormatException e) {
return new Location();
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null || value.toString().isEmpty() || !(value instanceof Location))
return "";
return String.valueOf(((Location) value).getId());
}
}
Console output:
// Getter method
INFO: Current value=ejb.locations.Location[id=null, name=null, latitude=0.0, longitude=0.0]
// Session Bean
INFO: Finding ejb.locations.Location with id=3
// Session Bean
INFO: ### Returning : ejb.locations.Location[id=3, name=mdmd, latitude=4.5, longitude=2.3]
// Converter
SEVERE: Converted 3 to ejb.locations.Location[id=3, name=mdmd, latitude=4.5, longitude=2.3]
// Getter method -> Where did my selected Location go ??
INFO: Current value=ejb.locations.Location[id=null, name=null, latitude=0.0, longitude=0.0]
Validation fails with the message "form:location: Validation Error: Value is not valid"
This error boils down to that the selected item does not match any of the available select item values specified by any nested <f:selectItem(s)> tag during processing of the form submit request.
As part of safeguard against tampered/hacked requests, JSF will reiterate over all available select item values and test if selectedItem.equals(availableItem) returns true for at least one available item value. If no one item value matches, then you'll get exactly this validation error.
This process is under the covers basically as below, whereby bean.getAvailableItems() fictionally represents the entire list of available select items as defined by <f:selectItem(s)>:
String submittedValue = request.getParameter(component.getClientId());
Converter converter = component.getConverter();
Object selectedItem = (converter != null) ? converter.getAsObject(context, component, submittedValue) : submittedValue;
boolean valid = false;
for (Object availableItem : bean.getAvailableItems()) {
if (selectedItem.equals(availableItem)) {
valid = true;
break;
}
}
if (!valid) {
throw new ValidatorException("Validation Error: Value is not valid");
}
So, based on the above logic, this problem can logically have at least the following causes:
The selected item is missing in the list of available items.
The equals() method of the class representing the selected item is missing or broken.
If a custom Converter is involved, then it has returned the wrong object in getAsObject(). Perhaps it's even null.
To solve it:
Ensure that exactly the same list is been preserved during the subsequent request, particularly in case of multiple cascading menus. Making the bean #ViewScoped instead of #RequestScoped should fix it in most cases. Also make sure that you don't perform the business logic in the getter method of <f:selectItem(s)>, but instead in #PostConstruct or an action event (listener) method. If you're relying on specific request parameters, then you'd need to explicitly store them in the #ViewScoped bean, or to re-pass them on subsequent requests by e.g. <f:param>. See also How to choose the right bean scope?
Ensure that the equals() method is implemented right. This is already done right on standard Java types such as java.lang.String, java.lang.Number, etc, but not necessarily on custom objects/beans/entites. See also Right way to implement equals contract. In case you're already using String, make sure that the request character encoding is configured right. If it contains special characters and JSF is configured to render the output as UTF-8 but interpret the input as e.g. ISO-8859-1, then it will fail. See also a.o. Unicode input retrieved via PrimeFaces input components become corrupted.
Debug/log the actions of your custom Converter and fix it accordingly. For guidelines, see also Conversion Error setting value for 'null Converter' In case you're using java.util.Date as available items with <f:convertDateTime>, make sure that you don't forget the full time part in the pattern. See also "Validation Error: Value is not valid" error from f:datetimeConverter.
See also:
Our selectOneMenu wiki page
How to populate options of h:selectOneMenu from database?
Make multiple dependent / cascading selectOneMenu dropdown lists in JSF
If anyone can throw some troubleshooting/debugging tips for this sort of problem it would be greatly appreciated.
Just ask a clear and concrete question here. Do not ask too broad questions ;)
In my case I forgot to implement a correct get/set methods. It happened because I have changed a lot of attributes along the development.
Without a proper get method, JSF canĀ“t recover your selected item, and happens what BalusC said at item 1 of his answer:
1 . The selected item is missing in the list of available items. This can happen if the list of available items is served by a request scoped bean which is not properly reinitialized on subsequent request, or is incorrectly doing the business job inside a getter method which causes it to return a different list in some way.
This can be a Converter Issue or else DTO issue.
Try to solve this, by adding hashCode() and equals() methods in your object DTO; In the above scenario you can generate these methods within the Location object class which indicate as the 'DTO' here.
Example:
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Location other = (Location) obj;
if (id != other.id)
return false;
return true;
}
Please note that the above example is for an 'id' of type 'long'.
I'm trying to set the date of birth of a person using jQuery Datepicker. However, all I get is that the Property dateOfBirth must be a valid Date.
So, originally, my controller looks like this:
def update(Person personInstance) {
if (personInstance == null) {
// do Something
return
}
if (personInstance.hasErrors()) {
respond personInstance.errors, view: 'edit'
return
}
// do the rest
}
I figured out, that with jQuery I should use a SimpleDateFormat object in order to generate a proper Date object. Nevertheless, even if I directly assign a new Date object to dateOfBirth and subsequently validating the personInstance domain object - like in the following code segment - I still get the Property dateOfBirth must be a valid Date error.
def update(Person personInstance) {
if (personInstance == null) {
// do Something
return
}
// added code
personInstance.dateOfBirth = new Date()
personInstance.validate()
// added code
if (personInstance.hasErrors()) {
respond personInstance.errors, view: 'edit'
return
}
// do the rest
}
Thank you for any help :)
The reason why you are still seeing errors is because validation is automatically called after binding your command/domain object when the method is called.
Use personInstance.clearErrors() before calling personInstance.validate() manually to clear out any existing binding/validation errors. You can see more about this in the documentation.
I'm trying to see if I need to write a custom IHttpRouteConstraint or if I can wrestle with the built-in ones to get what I want. I can't see to find any good documentation on this anywhere.
Basically, here's my action:
[Route("var/{varId:int:min(1)}/slot/{*slot:datetime}")]
public async Task<HttpResponseMessage> Put(int varId, DateTime slot)
{
...
}
What I want is to be able to call it like this:
PUT /api/data/var/1/slot/2012/01/01/131516 and have the framework bind 19 to var id and a DateTime with a value of "Jan 1st, 2012, 1:15:16pm" as the "slot" value.
Following the guide from here: http://www.asp.net/web-api/overview/web-api-routing-and-actions/create-a-rest-api-with-attribute-routing I am able to get it to work by passing in just the date segments, i.e. PUT /api/data/var/1/slot/2012/01/01 or PUT /api/data/var/1/slot/2012-01-01, but that only gives me a data value, no time components.
Something tells me that trying to pass in time in any sane way through URI segments is a bad idea, but I'm not sure why it'd be a bad idea, besides the ambiguity regarding local vs UTC times.
I've also tried constraining the datetime constraint with a regex, e.g. {slot:datetime:regex(\\d{4}/\\d{2}/\\d{2})/\\d{4})} to try to get it to parse something like 2013/01/01/151617 as a DateTime, but to no avail.
I'm pretty sure I can get this to work with a custom IHttpRouteConstraint, I just don't want to do something that might be built in.
Thanks!
an option is to pass the DateTime as query string parameters (see [FromUri]
e.g.
[Route("api/Customer/{customerId}/Calls/")]
public List<CallDto> GetCalls(int customerId, [FromUri]DateTime start, [FromUri]DateTime end)
this will have a signature of
GET api/Customer/{customerId}/Calls?start={start}&end={end}
Create the query string dates with
startDate.ToString("s", CultureInfo.InvariantCulture);
query string will look like
api/Customer/81/Calls?start=2014-07-25T00:00:00&end=2014-07-26T00:00:00
Web API datetime constraint doesn't do anything special regarding parsing datetime as you can notice below(source code here).
If your request url is like var/1/slot/2012-01-01 1:45:30 PM or var/1/slot/2012/01/01 1:45:30 PM, it seems to work fine...but I guess if you need full flexibility then creating a custom constraint is the best option...
public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
{
if (parameterName == null)
{
throw Error.ArgumentNull("parameterName");
}
if (values == null)
{
throw Error.ArgumentNull("values");
}
object value;
if (values.TryGetValue(parameterName, out value) && value != null)
{
if (value is DateTime)
{
return true;
}
DateTime result;
string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
return DateTime.TryParse(valueString, CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
}
return false;
}
I have a View Model called SignUp with the EmailAddress property set like this:
[Required]
[DuplicateEmailAddressAttribute(ErrorMessage = "This email address already exists")]
public string EmailAddress { get; set; }
and the custom validator looks like this:
public class DuplicateEmailAddressAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
PestControlContext _db = new PestControlContext();
int hash = value.ToString().GetHashCode();
if (value == null)
{
return true;
}
if (_db.Users.Where(x => x.EmailAddressHash == hash).Count() > 0)
return false;
else
return true;
}
}
The problem I'm having is that if the user leaves the email address field blank on the sign up form the application is throwing a null reference exception error (I think it's looking for "" in the database and can't find it). What I don't understand is why this isn't being handled by the Required attribute - why is it jumping straight into the custom validator?
The Required attribute would have resulted in an error being added to the model state. It will not short-circuit the execution though. The framework continues to run other validators for the simple reason that all the errors about the request need to be sent out in a single shot. Ideally, you wouldn't want the service to say something is wrong to start with and when the user re-submits the request after making a correction, the service comes back and say some other thing is wrong and so on. It will be an annoyance, I guess.
The NullReferenceException is thrown because value.ToString() is called before the check against null. As you need the hash variable only after the check, you can solve this by reordering the statements:
if (value == null)
{
return true;
}
int hash = value.ToString().GetHashCode();
In addition, you could also move the PestControlContext after the check against null and use a using statement to dispose of it properly.
As also #Baldri pointed out, each validator can add Error messages and all of them are run, even if a previous one already signaled the data to be invalid. Furthermore, I'd not rely on that the validations are run in the order that you specify when marking the property with the attributes (some frameworks implement their own attribute ordering mechanism in order to assert that the order is deterministic, e.g. priorities or preceding attributes).
Therefore, I suggest reordering the code in the custom validator is the best solution.