Date Field validation issues - drupal-7

The date field doesn't get validated for a format like 2013-02-13, but it works for 2013-12-12. Leading zero seems to be creating problem in any node form. I have "clientside validation" module on. I couldn't find anything related to this bug/issue anywhere, so I am posting here.
Can anyone help me?

There is issue in clientside validation js due to using of parseInt for validating a month & day value of a date. just replace with it
jQuery.validator.addMethod("dateFormat", function(value, element, param) {
var parts = value.split(param.splitter);
var expectedpartscount = 0;
var day = parseInt(parts[param.daypos], 10);
var month = parseInt(parts[param.monthpos], 10);
month = month - 1;
var year = parseInt(parts[param.yearpos], 10);
var date = new Date();
var result = true;
/* if (day.toString().length !== parts[param.daypos].length){
result = false;
}
if (month.toString().length !== parts[param.monthpos].length){
result = false;
}*/
if (year.toString().length !== parts[param.yearpos].length){
result = false;
}
if (param.yearpos !== false){
expectedpartscount++;
date.setFullYear(year);
if (year !== date.getFullYear()) {
result = false;
}
}
if (param.monthpos !== false) {
expectedpartscount++;
date.setMonth(month);
if (month !== date.getMonth()) {
result = false;
}
}
if (param.daypos !== false) {
expectedpartscount++;
date.setDate(day);
if (day !== date.getDate()) {
result = false;
}
}
if (expectedpartscount !== parts.length) {
result = false;
}
return this.optional(element) || result;
}, jQuery.format('The date is not in a valid format'));

Related

Filtering dates to within 7 days

I have a working date filter that accepts a date string like 2018-02-09T19:35:54+00:00 and orders events by date. I would like my filter to only push items in the next 7 days. I feel like I have a basic arithmetic error in my code.
function dashCalDateFilter() {
return function(collection, key) {
let output = [];
let keys = [];
let sevenDays = Date.now() + 604800000;
angular.forEach(collection, function(item) {
var ikey = item[key];
if (keys.indexOf(ikey) === -1) {
keys.push(ikey);
item['isFirst'] = true;
}
console.log(item.start_time);
if (Date.now() - Date.parse(item.start_time) < sevenDays){
output.push(item);
};
});
return output;
};
}
export default dashCalDateFilter;
My math was a bit off. Here is the working version
function dashCalDateFilter() {
return function(collection, key) {
let output = [];
let keys = [];
let sevenDays = 604800000;
angular.forEach(collection, function(item) {
var ikey = item[key];
if (keys.indexOf(ikey) === -1) {
keys.push(ikey);
item['isFirst'] = true;
}
if ((Date.parse(item.start_time) - Date.now()) < 604800000){
output.push(item);
} else {
console.log('in >7 days');
console.log(Date.parse(item.start_time) - Date.now());
};
});
return output;
};
}
export default dashCalDateFilter;

How to add thousand separating commas for numbers in angularJS?

I simply want to convert a string of numbers to a number which will be displayed using thousand separated commas.
var value = "123456";
I want to display "123,465" in a grid.
I have looked some documentation on this but everything is about displaying it in HTML.
I want to display this in a dynamic grid.
function numberRenderer (params) {
return new Number (params.value);
}
I want to format the number so that I can convert that into a string for display.
Use a filter ...
HTML usage
{{ number_expression | number : fractionSize}}
Js usage
$filter('number')(number, fractionSize)
I appreciated the answer from #jbrown, but I was also hoping to find some type of solution to add commas to an input field as the user enters numbers. I ended up finding this directive which proved to be exactly what I needed.
HTML
<input type="text" ng-model="someNumber" number-input />
JAVASCRIPT
myApp.directive('numberInput', function($filter) {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.push(function(modelValue) {
return setDisplayNumber(modelValue, true);
});
// it's best to change the displayed text using elem.val() rather than
// ngModelCtrl.$setViewValue because the latter will re-trigger the parser
// and not necessarily in the correct order with the changed value last.
// see http://radify.io/blog/understanding-ngmodelcontroller-by-example-part-1/
// for an explanation of how ngModelCtrl works.
ngModelCtrl.$parsers.push(function(viewValue) {
setDisplayNumber(viewValue);
return setModelNumber(viewValue);
});
// occasionally the parser chain doesn't run (when the user repeatedly
// types the same non-numeric character)
// for these cases, clean up again half a second later using "keyup"
// (the parser runs much sooner than keyup, so it's better UX to also do it within parser
// to give the feeling that the comma is added as they type)
elem.bind('keyup focus', function() {
setDisplayNumber(elem.val());
});
function setDisplayNumber(val, formatter) {
var valStr, displayValue;
if (typeof val === 'undefined') {
return 0;
}
valStr = val.toString();
displayValue = valStr.replace(/,/g, '').replace(/[A-Za-z]/g, '');
displayValue = parseFloat(displayValue);
displayValue = (!isNaN(displayValue)) ? displayValue.toString() : '';
// handle leading character -/0
if (valStr.length === 1 && valStr[0] === '-') {
displayValue = valStr[0];
} else if (valStr.length === 1 && valStr[0] === '0') {
displayValue = '';
} else {
displayValue = $filter('number')(displayValue);
}
// handle decimal
if (!attrs.integer) {
if (displayValue.indexOf('.') === -1) {
if (valStr.slice(-1) === '.') {
displayValue += '.';
} else if (valStr.slice(-2) === '.0') {
displayValue += '.0';
} else if (valStr.slice(-3) === '.00') {
displayValue += '.00';
}
} // handle last character 0 after decimal and another number
else {
if (valStr.slice(-1) === '0') {
displayValue += '0';
}
}
}
if (attrs.positive && displayValue[0] === '-') {
displayValue = displayValue.substring(1);
}
if (typeof formatter !== 'undefined') {
return (displayValue === '') ? 0 : displayValue;
} else {
elem.val((displayValue === '0') ? '' : displayValue);
}
}
function setModelNumber(val) {
var modelNum = val.toString().replace(/,/g, '').replace(/[A-Za-z]/g, '');
modelNum = parseFloat(modelNum);
modelNum = (!isNaN(modelNum)) ? modelNum : 0;
if (modelNum.toString().indexOf('.') !== -1) {
modelNum = Math.round((modelNum + 0.00001) * 100) / 100;
}
if (attrs.positive) {
modelNum = Math.abs(modelNum);
}
return modelNum;
}
}
};
});
AngularJS Directive was found from: AngularJS number input formatted view
https://jsfiddle.net/benlk/4dto9738/
Very appreciative of what Anguna posted. The only thing it was missing for me was handling the decimal places like currency. I wanted it to automatically add 2 decimal places to the displayed value. However, this should only occur on initial display and then again when leaving a field. I updated the code to handle that scenario.
var app = angular.module("myApp", []);
app.directive('currencyInput', function ($filter) {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.push(function (modelValue) {
var displayValue = setDisplayNumber(modelValue, true);
displayValue = setDecimal(displayValue);
return displayValue;
});
// it's best to change the displayed text using elem.val() rather than
// ngModelCtrl.$setViewValue because the latter will re-trigger the parser
// and not necessarily in the correct order with the changed value last.
// see http://radify.io/blog/understanding-ngmodelcontroller-by-example-part-1/
// for an explanation of how ngModelCtrl works.
ngModelCtrl.$parsers.push(function (viewValue) {
setDisplayNumber(viewValue);
return setModelNumber(viewValue);
});
// occasionally the parser chain doesn't run (when the user repeatedly
// types the same non-numeric character)
// for these cases, clean up again half a second later using "keyup"
// (the parser runs much sooner than keyup, so it's better UX to also do it within parser
// to give the feeling that the comma is added as they type)
elem.bind('keyup focus', function () {
setDisplayNumber(elem.val());
});
elem.bind('blur', function () {
// Add Decimal places if they do not exist
var valStr = elem.val().toString();
valStr = setDecimal(valStr);
elem.val(valStr);
});
function setDisplayNumber(val, formatter) {
var valStr, displayValue;
if (typeof val === 'undefined') {
return 0;
}
valStr = val.toString();
displayValue = valStr.replace(/,/g, '').replace(/[A-Za-z]/g, '');
displayValue = parseFloat(displayValue);
displayValue = (!isNaN(displayValue)) ? displayValue.toString() : '';
// handle leading character -/0
if (valStr.length === 1 && valStr[0] === '-') {
displayValue = valStr[0];
} else if (valStr.length === 1 && valStr[0] === '0') {
displayValue = '';
} else {
displayValue = $filter('number')(displayValue);
}
// handle decimal
if (!attrs.integer) {
if (displayValue.indexOf('.') === -1) {
if (valStr.slice(-1) === '.') {
displayValue += '.';
} else if (valStr.slice(-2) === '.0') {
displayValue += '.0';
} else if (valStr.slice(-3) === '.00') {
displayValue += '.00';
}
} // handle last character 0 after decimal and another number
else {
if (valStr.slice(-1) === '0') {
displayValue += '0';
}
}
}
if (attrs.positive && displayValue[0] === '-') {
displayValue = displayValue.substring(1);
}
if (typeof formatter !== 'undefined') {
return (displayValue === '') ? 0 : displayValue;
} else {
elem.val((displayValue === '0') ? '' : displayValue);
}
}
function setModelNumber(val) {
var modelNum = val.toString().replace(/,/g, '').replace(/[A-Za-z]/g, '');
modelNum = parseFloat(modelNum);
modelNum = (!isNaN(modelNum)) ? modelNum : 0;
if (modelNum.toString().indexOf('.') !== -1) {
modelNum = Math.round((modelNum + 0.00001) * 100) / 100;
}
if (attrs.positive) {
modelNum = Math.abs(modelNum);
}
return modelNum;
}
function setDecimal(val) {
// Add Decimal places if they do not exist
var valStr = val.toString();
// If no decimal then add it
if (valStr.indexOf('.') === -1) {
valStr += '.00';
}
else {
var decimalDigits = valStr.length - (valStr.indexOf('.') + 1);
var missingZeros = 2 - decimalDigits;
for (var i = 1; i <= missingZeros; i++) {
valStr += '0';
}
}
return valStr;
}
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<div ng-app="myApp">
<input type="text" ng-model="myModelValue" currency-input />
</div>

Ag-Grid Filter Comma

im using ag-Grid, but there is a issue when it filters my data, when i filter my data in the price column, it only works with numbers dot and not with commas.
Link: https://plnkr.co/edit/LDdrRbANSalvb4Iwh5mp?p=preview
Practical Example:
In the Price column select box equal and above insert "1.5" and than try inserting "1,5"
This is because this filter is a native one.
If you want to handle custom behaviour, define your own filter.
Documentation : https://www.ag-grid.com/angular-grid-filtering/index.php
A quick and dirty solution would be to monkey patch the NumberFilter like this :
NumberFilter.prototype.doesFilterPass = function (node) {
if (this.filterNumber === null) {
return true;
}
var value = this.valueGetter(node);
if (!value && value !== 0) {
return false;
}
var valueAsNumber;
if (typeof value === 'number') {
valueAsNumber = value;
}
else {
valueAsNumber = parseFloat(value.replace(',','.'));
}
switch (this.filterType) {
case EQUALS:
return valueAsNumber === this.filterNumber;
case LESS_THAN:
return valueAsNumber < this.filterNumber;
case GREATER_THAN:
return valueAsNumber > this.filterNumber;
default:
// should never happen
console.warn('invalid filter type ' + this.filterType);
return false;
}
};
Then changed line is here :
valueAsNumber = parseFloat(value.replace(',','.'));
So i found the problem, first i had to convert the value has a string than i needed to replace the dot by the comma, the problem with the answer above was first because of the data type and than the order of the properties of the replace function, but the problem now is that is not filtering correctly, if i search using equal option if gives me 2 values, instead a fixed one, code looks something like this:
Code:
NumberFilter.prototype.doesFilterPass = function (node) {
if (this.filterNumber === null) {
return true;
}
var value = this.valueGetter(node);
if (!value && value !== 0) {
return false;
}
var valueAsNumber;
if (typeof value === 'number') {
value = value.toString()
valueAsNumber = parseFloat(value.replace('.',','));
}
else {
valueAsNumber = parseFloat(value.replace('.',','));
}
switch (this.filterType) {
case EQUALS:
return valueAsNumber === this.filterNumber;
case LESS_THAN:
return valueAsNumber < this.filterNumber;
case GREATER_THAN:
return valueAsNumber > this.filterNumber;
default:
// should never happen
console.warn('invalid filter type ' + this.filterType);
return false;
}
};
Possible Solution:
NumberFilter.prototype.onFilterChanged = function () {
var filterText = utils_1.default.makeNull(this.eFilterTextField.value);
if (filterText && filterText.trim() === '') {
filterText = null;
}
var newFilter;
if (filterText !== null && filterText !== undefined) {
console.log(filterText);
// replace comma by dot
newFilter = parseFloat(filterText.replace(/,/g, '.'));
console.log(newFilter);
}
else {
newFilter = null;
}
if (this.filterNumber !== newFilter) {
this.filterNumber = newFilter;
this.filterChanged();
}
};

show and hide warnings in angularjs

I am new to angularjs, I want to show and hide a message with data-ng-show (it is a warning message) based on a condition in my javascript is there anyway to handle it like validations set some functions like ngModel.$setValidity('range', true)- I dont want it to act like validation and prevent submitting.
this is my code:
var showMessage = (value) => {
legalDate = new Date();
legalDate.setFullYear(legalDate.getFullYear() - 21);
var dateValue = new Date(year, month, day);
if (value != null && value !== "" && dateValue.getTime() > legalDate.getTime()) { //DOB indicates >12 and <21
// $('.under21').show(); ==> something like this: ngModel.$setValidity('range', true);
}
else {
// $('.under21').hide();
}
return value;
}
Thanks
You can set a scope variable in the condition and then use that in the html markup. Something like this:
//Set the scope variable;
$scope.showElement = false;
var showMessage = (value) => {
legalDate = new Date();
legalDate.setFullYear(legalDate.getFullYear() - 21);
var dateValue = new Date(year, month, day);
if (value != null && value !== "" && dateValue.getTime() > legalDate.getTime()) { //DOB indicates >12 and <21
$scope.showElement = true;
}
else {
$scope.showElement = false;
}
return value;
}
And in the html markup say you have a span on which you need to show/hide:
<span class="under21" ng-show="showElement"></span>

Angular Filter by Date/Time Range

I'm trying to build an event date filter by passing in a time range. I was able to filter for events that are the same date as today but need help to filter events from last week, last month, etc...
$scope.eventDateFilter = function(column) {
if(column === 'today') {
$scope.dateRange = $scope.dateToday;
} else if (column === 'pastWeek') {
//need logic
} else if (column === 'pastMonth') {
//need logic
} else if (column === 'future') {
//need logic
} else {
$scope.dateRange = "";
}
}
Here's my fiddle:
http://jsfiddle.net/c6BfQ/3/
Your help is greatly appreciated.
I would use a custom filter. Here is one I used to filter things created in the last two days, it should give you an idea of how to do yours.
.filter('dateFilter', function() {
return function (objects) {
var filtered_list = [];
for (var i = 0; i < objects.length; i++) {
var two_days_ago = new Date().getTime() - 2*24*60*60*1000;
var last_modified = new Date(objects[i].date_created).getTime();
if (two_days_ago <= last_modified) {
filtered_list.push(objects[i]);
}
}
return filtered_list;
}
});

Resources