parsley.js - custom validation for date field - javascript

I have been reading the parsley.js docs and I have tried to write a custom validator to validate if a date is greater than todays date.
I have the conditional code written, but I am completly confused about how to apply the conditional error message.
I have completed the task with a parsley maxlength validator, but realise that this is less than perfect.
How do I write the custom validation with parsley?
Here is my js/jq code that dynamically adds & deletes the validation using the maxlength:
if(formattedStartDate > todaysDate) {
$('#id_voluntary_start_date').attr('data-parsley-maxlength', '1');
$('#id_voluntary_start_date').attr('data-parsley-maxlength-message', '{% trans "Commencement Date must not be greater than today." %}');
$('#id_voluntary_start_date').parsley();
} else {
$('#id_voluntary_start_date').attr('data-parsley-maxlength', '50');
}
Any help with implementing the custom validation would be appreciated.

First of all set one hidden textbox and store today's date in it and just write below code on date field you want to check.
data-parsley-dlte = "#hiddentextboxid",
data-parsley-dlte_message = "Your custom message"
Don't forget to set parsley on the form in which you have your dom elements.
If this doesn't work check the version of parsley js.
Hope this is helpful.

All you need to do is register your custom validator either globally (in window.ParsleyConfig) or for your particular form as follows:
myForm.parsley({
validators: {
custom: function (value) {
var now = new Date();
var date = new Date(value);
return date < now;
}
},
messages: {
custom: 'Commencement Date must not be greater than today'
}
});
Here is jsFiddle with a sample

Related

Restrict changing a date field to further date from its current value Dynamics CRM?

I want to achieve the following, restrict changing a date field to further date from its current value, in Dynamics CRM via JavaScript.
Below is my JavaScript code, im pretty new to JavaScript Dynamics development, below is my code, by the way its not throwing an alert, is it coded properly? - apologies if the question doesnt make sense.
Why isn't it throwing an alert, when I enter a date future from current value?
function test(executionContext) {
formContext = executionContext.getFormContext();
var fielddate = formContext.getAttribute('fielddate').getValue();
if (fielddate != null) {
fielddate.setHours(0, 0, 0, 0);
//The current date
var currentDate = new Date();
currentDate.setHours(0, 0, 0, 0);
if (fielddate > currentDate) {
alert("You can't enter future date");
}
}
}
the JavaScript code is correct, you may want to check the field name (the one you are assigning to fielddate variable) because if it's null then your code is not executed.
Instead of alert I would write
Xrm.Navigation.openAlertDialog(text: "You can't enter future date");
because it's the supported way to display alerts (https://learn.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-navigation/openalertdialog)
after the message you should also clear the field, so the user can set a new value (otherwise the wrong value will be stay there)
formContext.getAttribute('fielddate').setValue(null);

I am trying to validate that one date is between 2 other dates using suitescript when being edited inline on a saved search

Validate inline edit on a saved search, suitescript 1.0
I have the validation working for non-inline edits when the change is made on the record itself. I am looking to get the same validation online when an edit is made on the saved search as an inline edit. I have 3 date fields, a ship, cancel, and expected date. The cancel date needs to be between the ship date and the expected date. I am using the following code. TNHelper.inRageDateCheck just returns true if the 3rd date is between the first two dates.
Edit Example
function saveRecord_Functions() {
var noProblem = true, alertmsg = '';
// EXPECTED DATE Required only in Form "TN Purchase Order"
if (nlapiGetFieldValue('customform') != 102 || type != 'xedit') return true;
var helper = new TNHelper();
if (helper.inRageDateCheck(nlapiGetFieldValue('custbody_startshipdate')
,nlapiGetFieldValue('custbody_tn_po_expecteddate')
,nlapiGetFieldValue('custbody_tn_po_canceldate'))){
noProblem = true;
}else{
alertmsg = 'Cancel Date must be between Start Ship Date and Expected Date.';
}
if(alertmsg.length>0){
alert(alertmsg);
return;
}
return noProblem;
}
I would like it to pop alertmsg when an invalid cancel date is put into the field and attempted to be saved.
This will not work on the client script save record entry point; the xedit context validation is only available for user event scripts. You can add validation with a UE script, but unfortunately you will not be able to send an alert to the user via alert(). For more information on how to do this, check out this question: Validate In-Line Edits in Netsuite

Jquery how to validate input on specific characters and to follow specific pattern

I have an input field where users are supposed to enter their date of birth. The pattern which I want to use is for example 24-06-2019. So, now I want to make some kind of validation, and if the user entered the wrong pattern there should be some kind of alert. How can I achieve that?
Here is what I got so far:
$('input[name="dateOfBirth"]').on("keyup", () => {
let current_value = $('input[name="dateOfBirth"]').val();
// some validation here?
});
Really simple regex:
if (/\d{2}-\d{2}-\d{4}/.test(current_value)) {
//Date is of correct format
}
If you want to validate the date itself, then just create a new date and check if it's invalid:
const validDate = new Date();
const invalidDate = new Date("abc");
console.log(validDate == "Invalid Date");
console.log(invalidDate == "Invalid Date");

JavaScript Date Format for ColdFusion Date Field

Is it possible to add something to this function that will set up the date format and require the user to enter MM/DD/YYYY? MASK is not working..
Fee Calculator Function:
function getDatePrice() {
var datePrice = 0;
var theForm = document.forms.form;
var purchasedate = theForm.elements.purchasedate;
var date = new Date(purchasedate.value);
if (Object.prototype.toString.call(date) !== '[object Date]') {
date = new Date();
}
var today = new Date();
var diffMilli = today - date;
var diffDays = Math.floor(diffMilli / 1000 / 60 / 60 / 24); // ..Divide!
if (diffDays > 30) {
datePrice = 20;
}
else {
datePrice= 0;
}
return datePrice;
}
Calling Function:
function calculateTotal()
{
var titleFees = getDatePrice();
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Estimated Transfer Fees $"+titleFees;
}
Input Button: (Requiring ColdFusion):
<cfinput
type="datefield"
name="purchasedate"
width="130"
required="yes"
message="Please enter purchase date."
value="#dateformat(now(),"mm/dd/yyyy")#"
oninput="calculateTotal();"
>
I am going to go ahead and add an answer here since another question has been opened regarding the same issue. I believe the problem is that the mask attribute on the <cfinput type="datefield" ... code only works when using Flash forms - documentation reference.
I have emphasized the text from that documentation below:
Masking cfcalendar and datefield input
In the cfcalendar tag and the Flash format datefield input control, you use the following masks to determine the format of the output. You can use uppercase or lowercase characters in the mask:
...
The following pattern specifies that the Flash form sends the date selected using a datefield input control to ColdFusion as text in the format 04/29/2004:
<cfinput name="startDate" type="datefield" label="date:" mask="mm/dd/yyyy"/>
Since you are not using a Flash form the mask is not working for you. You could try switching to a regular <cfinput type="text" ... input and change your mask to something like "99/99/9999". That would give you the correct format but the user could still enter invalid dates so you would need additional code to catch that.
In the comments you stated:
What is strange is that I have others that actually work like.. <cfinput type="text" name="odate" id="odate" validateat="onSubmit" validate="noblanks" required="yes" message="Please enter odometer date." value="" mask="99/99/9999" placeholder="08/05/2014"> but for some reason it is just the datefield that will not except the MASK
Notice that you are using a "text" input here so the mask works (as in my previous comment). It is only with the "datefield" type that the mask does not work; unless you are using a Flash form.
This is just another example of why using the built-in ColdFusion UI tags is not a good idea. They work for very simple examples but when you need more customization they fail you. You would be better off to use a JavaScript library (like jQuery) for client side validation. Adobe's own Ben Forta acknowledged this several years ago. And the ColdFusion-UI-the-Right-Way project was started because of this as well.
EDIT
Adam pointed out another reference in the ColdFusion documentation that reinforces my point. I have emphasized the text from that documentation below:
Masking input data
In HTML and Flash forms, the mask attribute controls the format of data that can be entered into a text field or that is selected in a datefield input control calendar. In HTML format, it does not prevent users from typing a date that does not follow the mask into a datefield input control. You can combine masking and validation on a field.

Bootstrap DatePicker - Validate Date

I have a bootstrap datepicker set up such that the startDate = '1/1/1990', but if the user enters the date manually in the text box to something such as 1/1/201 (likely mistype of 1/1/2014), the date is just blanked out when they change focus. Is there a way such that if they attempt to leave the field with an invalid date that instead of having a blank field that I can specify something like today's date, or even change the background color and not allow for the user to leave that field?
Thank you for your help.
You can also set the date field to readonly, in this way user can only select correct date format from datepicker.
example:
http://www.w3schools.com/tags/att_input_readonly.asp
You can use the jquery validation plugin for the color, showing msg for the invalid date. And in that case for validating the date value with present date you have to add a custom validation method to it like :-
$.validator.addMethod("presentDate", function(value, element) {
if(new Date(value).getTime() >= new Date().getTime()){
return true;
} else {
return false;
}
});
I have figured out that I can simply detect when the value of the date has been set to '' and go from there with what I want to change:
$('#StartDate').change(function()
{
if (this.value === '')
{
alert('Start date is now set to empty string, do work here');
}
});

Categories