lightning:input Date Field validation - salesforce

I am trying to use Standard Date picker using below component but however I want to display custom error message when the enterted date is not in the speciied min & max range. But I am not able to achieve it as I could see the standard error message. I implemented the same by referring to : https://developer.salesforce.com/docs/component-library/bundle/lightning:input/example and in this link I can see that the custom error messages can be shown. But nothing worked for me can anyone please help.
https://developer.salesforce.com/docs/component-library/bundle/lightning:input/documentation
<lightning:input aura:id="field
type="date"
name="MyDatefield"
label="MyDateField"
value="2017-09-07"
min="2017-09-05"
messageWhenRangeUnderflow="Select correct date range1"
max="2017-09-22"
messageWhenRangeOverflow="Select correct date range2"
onchange="{!c.checkValidity }"
</aura:component>

This was asked 1 month back but sharing the answer if anybody else runs across this. Use lightning's setCustomValidity() and reportValidity() methods.
Component:
<aura:component >
<lightning:input aura:id="field"
type="date"
name="MyDatefield"
label="MyDateField"
value="2017-09-07"
min="2017-09-05"
max="2017-09-22"
onblur ="{!c.checkValidity }"
/>
</aura:component>
Controller:
({
checkValidity : function(component, event, helper) {
var inputCmp = component.find("field");
inputCmp.setCustomValidity(""); //reset error
var value = inputCmp.get("v.value");
console.log('value: '+value);
var lowerRange = new Date("2017/09/05");
var higherRange = new Date("2017/09/22");
if(!inputCmp.checkValidity()){
if(Date.parse(value)){
if (Date.parse(value) < lowerRange) {
inputCmp.setCustomValidity("Select correct date range1");
}else if (Date.parse(value) > higherRange){
inputCmp.setCustomValidity("Select correct date range2");
}
}else{
inputCmp.setCustomValidity("Invalid value");
}
}
inputCmp.reportValidity();
}
})

Related

Define default date and catch date elected by user react

I want by default display the current date and all information linked to,
and in case of another date choose by user display corresponding info.
const [dateCourante, setDateCourante] = useState(new Date());
const onSetDate = (e) => {
setDateCourrante(e.target.value);
}
I display the date as a string :
<p>
{ dateCourrante.toDateString() }.
</p>
and this input to set/display the same date :
<input
type="date"
name="date"
id="date"
value={dateCourrante}
onChange={onSetDate} />
But thatdont work
please can you help achieve the goal by explain me where i have wrong ?, thanks.

How to resolve min and max date input in React Js?

I've created a function that return a substraction or an addition from current Date, and set the result in the min or max of date input :
My function :
SubDate = (subDay) => {
let tgDate = new Date();
tgDate.setDate(tgDate.getDate() + subDay)
return tgDate.toLocaleDateString();
}
My input :
<input type="date" id="dateInput" min={this.SubDate(-7)} max={this.SubDate(7)} />
The function is working. In the navigator's inspector, I see the min and max of the input like so :
<input type="date" id="dateInput" min="13/09/2020" max="27/09/2020">
But when I try to select a date, It does'nt prevent me to choose the min date and the max date.
Can I resolve that ? Or using DateTimePicker instead of that.
Thank you.
I am not sure if you ended up resolving this or not but for reference ,
var today = new Date().toISOString().split('T')[0];
<input type="date" onChange={this.handleChange} max={today} />

Manually entered date is not being validated - uib datepicker popup

I am using 0.14.3 angular-bootstrap version. I have issues with min and max validation for uib-datepicker-popup. min-date and max-date are working as expected, dates are disabled on popup view. However if I enter manually dates inside input text validation is not there...I added even min and max attributes but nothing again. When check in form.$error and there is not validation error.
<input id="projEndDate" class="form-control date-picker"
uib-datepicker-popup="{{planningvm.format}}"
show-button-bar="false"
ng-model="reviewvm.review.projectedEndDt"
data-ng-click="planningvm.openDatePicker('projEndDate')"
placeholder="mm/dd/yyyy" name="projEndDate" show-weeks="false"
required is-open="planningvm.projEndDate.opened"
min="reviewvm.review.projectedStartDt"
min-date="reviewvm.review.projectedStartDt" />
<span data-ng-class="{'not-allowed input-group-addon' : !reviewvm.userReviewAssoc || !reviewvm.editMode, 'input-group-addon' : reviewvm.userReviewAssoc}"
data-ng-click="planningvm.openDatePicker('projEndDate')">
<div class="icon-calendar" id="icon-daterange-end" >
</div>
</span>
Is there some way that i can maybe check for date validation when user type manually in input and set that ng-model to min or max corresponding?
This appears to be a known issue when using the uib-datepicker-popup with input min and max validations: Datepicker input not validated for min and max when manually inserting date #4664 that they do not intend on fixing. I developed a workaround that performs the validations when the input value changes like so:
// watch date value
scope.$watch((scope) => {
//return object to watch.
return this.date;
}, (newValue: Date, oldValue: Date) => {
this.onValueChange();
});
private onValueChange() {
if (angular.isDefined(this.date) && this.date && !this.myForm.date.$error.date) {
this.myForm.date.$setValidity("min", moment(this.date).isSameOrAfter(this.minDate));
this.myForm.date.$setValidity("max", moment(this.date).isSameOrBefore(this.maxDate));
} else {
this.myForm.date.$setValidity("min", true);
this.myForm.date.$setValidity("max", true);
}
}

How to show month and year only in 720kb AngularJS Datepicker

I'm using this angularJS datepicker in my application and would like to know if there is a way to display only months and years in the calendar and remove the days?
This is how I'm using the datepicker:
<datepicker date-format="MM yy" button-prev-title="previous month" button-next-title="next month" button-prev="<i class='fa fa-arrow-left'></i>" button-next="<i class='fa fa-arrow-right'></i>" id="dtDate" name="dtDate" >
<input ng-model="dtDate" />
</datepicker>
I tried to add date-format="MM yy" but it only changes the selected date and not the datepicker itself.
I think you might be interested in using this git repository that I created.
https://github.com/morfsys/multiple-month-picker
This is how you can use it in your project:
HTML
<input type="text" multiple-month-picker />
JS
//Initiate your app by injecting 'mmp-morfsys'
var app = angular.module('app-name', ['mmp-morfsys'])
It helps you to select multiple months across multiple years. The best thing? It is on AngularJS.
I hope it helps you.
I have the same problem with angularjs-datepicker.
I used another datepicker: angularjs-material.
Here is how you can use it:
<md-datepicker ng-model="startDate" md-mode="month" md-placeholder="dd/MM/yyyy" md-date-locale="mylocale" md-open-on-focus></md-datepicker>
And then in your controller:
function pad(n) {return n < 10 ? "0"+n : n;}
$scope.mylocale = {
formatDate: function(date) {
var d=new Date(date);
if(isNaN(d.getTime())) {
return '';
} else {
return pad(d.getDate())+"/"+pad(d.getMonth()+1)+"/"+d.getFullYear();
}
},
parseDate: function(date) {
var ds = date.split('/');
var d=new Date(ds[2],ds[1]-1,ds[0]);
if(isNaN(d.getTime())&&d!=''){
return new Date(NaN);
} else {
return d;
}
} };
And it is working. Just make sure that you properly handle case when input is invalid (form.startDate.$invalid).
If someone has a solution for angularjs-datepicker, please let us know.

Is there a way for comparing dates on Valdr?

I'm using Valdr on my project and I need to validate that a date input "startDate" is before another date input "endDate".
<input id="startDate" name="startDate" type="text" ng-model="project.startDate"/>
<input id="endDate" name="endDate" type="text" ng-model="project.endDate"/>
I know that, without Valdr, this problem can be solved using a custom directive, as shown here: Directive for comparing two dates
I found a little unclear how to create a custom validator on Valdr that uses the values of other fields.
The answer is short but dissatisfactory: valdr does currently not support this. There is an open feature request on GitHub, though.
Until the feature gets implemented in valdr, you can use your own validator directive and kind of make it talk to valdr. The directive can require a 'form' and can get the names of the date models you want to compare. Then you do your logic to compare the two values and set the validity of the appropriate 'ngModelController'. Since you need to provide an error when setting the validity to that model, the error name will be your connection with valdr.
After that, you just only need to map the error in the 'valdrMessage' service:
.run(function (valdrMessage) {
valdrMessage.angularMessagesEnabled = true;
valdrMessage.addMessages({
'date': 'Invalid date!'
});
});
Valdr will show the message bellow the invalid field as usual.
Actually you can solve this through a custom validator, which can get another field and compare the values with each other. The code below is using the valdr-bean-validation for serverside generation of valodation.json.
If you want to use it without this, just look into the JS code and add the validator in your validation.json manually.
Java Annotation (serverside declaration of the valdr validator):
package validation;
#Documented
#Retention(RetentionPolicy.RUNTIME)
#Target({ ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR,
ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
public #interface DateFormat {
String message();
Class[] groups() default { };
String beforeFieldName();
}
Java Bean (usage of the annotation, this class has to be used in the generation of validation.json):
package pojo;
import validation.DateFormat;
public class RegistrationPojo implements BasePojo {
#NotNull(message = "message.date1.required")
private Date date1;
#NotNull(message = "message.date2.required")
#DateFormat(message = "message.date2.date", beforeFieldName = "date1")
private Date date2;
}
JS (implementation of the custom validator and registering it in valdr):
module.factory('validation.DateFormat', [
function () {
return {
name: 'validation.DateFormat',
validate: function (value, constraint) {
var minOk = true;
var maxOk = true;
var format = false; // constraint.pattern is mandatory
//do not validate for required here, if date is null, date will return true (valid)
console.log("my date validator called");
console.log(" beforeFieldName: " + constraint.beforeFieldName);
var field = document.querySelector('[name="' + constraint.beforeFieldName + '"]');
console.log("field value: " + (field ? field.value : "null"));
return (!field || value > field.value);
}
};
}]);
module.config([
"valdrProvider",
function(valdrProvider) {
valdrProvider.addValidator('validation.DateFormat');
}]);
You could go with this solution:
Have a bool value calculated upon changes in any of the date fields - a value indicating if the validation rule is met
Create a simple custom validator to check if that value is true or not
Register your validator and add a constraint for that calculated value
Place a hidden input for that calculated value anywhere you like your validation message to appear

Resources