Knockout JS Validation for Date of Birth less than 18 - javascript

Need help in building a function for my Project which will disable anybody from entering the date of birth less than 18 in the date of birth field.
A validation will work !! just need help in building a validation
htmlcode
<label>Date of Birth <span class="red-asterisk">*</span></label>
<input type="text" id="DOB" name="DateOfBirth" placeholder="&nbsp dd/mm/yyyy" data-bind="datePicker : Model.DateOfBirth, dateTimePickerOptions : {format: 'DD/MM/YYYY', maxDate: (new Date()).addDays(-6573), useCurrent : false}" />
js file code
self.Model.DateOfBirth = ko.observable().extend({
date: true,
required: {
params: true,
message: "Please enter a date"
}
});
where shall I change the code for validation or showing a validation age less than 18 years old not allowed to sign in?

You need to create knockout custom rule as follows
ko.validation.rules["DateValidation"] = {
validator: function (val) {
var ageDifMs = Date.now() - val.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
var year = Math.abs(ageDate.getUTCFullYear() - 1970);
return (year < 18);
},
message: " "
};
ko.validation.registerExtenders();
then you can add to your extend
self.Model.DateOfBirth = ko.observable().extend({
date: true,
required: {
params: true,
message: "Please enter a date"
},
DateValidation: {
message: "Override message"
}
});

Related

how to get rid of errorClass in start date if end date is correct validate jquery

I have start date and end date, HTML below:
<div class="wrapper">
<div class="form-group">
<label class="col-form-label col-sm-3 required">Start Date</label>
<div class="col-sm-9">
<input name="startDate" type="text" class="validation-invalid-label" value="03-10-2024">
</div>
</div>
<div class="form-group">
<label class="col-form-label col-sm-3 required">End Date</label>
<div class="col-sm-9">
<input name="endDate" type="text" class="valid" value="02-10-2025">
</div>
</div>
</div>
I set start date, for example, 03-10-2022 and end date 02-10-2023. Then I focus on start date and set it to 03-10-2024 which is not correct by validation(text becomes red). To solve it I set end date to 02-10-2025. End date becomes black as it must be but start date stays red(it becomes black only when I focus on it).My code below:
$(selector).validate({
rules: {
startDate: {
required: true
},
endDate: {
required: true,
dependsOnDate: {
comparisonDate: `input[name="startDate"]`,
method: 'isAfter'
}
}
},
messages: {
startDate: {
required: "Invalid date",
},
endDate: {
required: "Invalid date",
dependsOnDate: "Invalid date"
},
},
errorClass: 'validation-invalid-label',
successClass: 'validation-valid-label',
highlight: function(element, errorClass, validClass) {
$(element).addClass(errorClass).removeClass(validClass);
$(element).parents('.wrapper').addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
if (!_.some(_.keys(this.invalid), key => !_.isUndefined(this.invalid[key]) && this.invalid[key]!== false)) {
$(element).removeClass(errorClass).addClass(validClass);
$(element).parents('.wrapper').removeClass('has-error');
}
},
});
So I need to remove errorClass from start date if end date becomes correct. My custom method:
$.validator.addMethod("dependsOnDate", function(value, element, params) {
const givenDate = moment(value);
const comparisonDate = moment($(params.comparisonDate).val())
return givenDate[params.method](comparisonDate);
});

How to set max date in a kendodatepicker every time another date is chosed

i have two kendodatepickers "startDate" and "endDate". I want every time the user set a date in startdate, establish the max date one month forward from the selected date to pick in endDate datepicker.
I am setting up the first time in this way:
$("#datStartDate").kendoDatePicker({
start: "month",
depth: "year",
format: "dd/MM/yyyy",
dateInput: true,
change: (e) => {
return moc.rangeStartDate("datStartDate", "datEndDate");
},
min: new Date(1900, 0, 1),
max: new Date(),
value: new Date()
});
$("#datEndDate").kendoDatePicker({
start: "month",
depth: "year",
format: "dd/MM/yyyy",
dateInput: true,
max: new Date(),
change: (e) => {
return moc.rangeEndDate("datStartDate", "datEndDate");
},
value: new Date()
});
I tried this to set the max value, each time the startDate picker is cheanged:
$("#datStartDate").change(() => {
let startDate = ($("#datStartDate").val()).split("/");
console.log("cambio de fecha", parseInt(startDate[2]), parseInt(startDate[1]), parseInt(startDate[0]))
let datePicker = $("#datEndDate").data("kendoDatePicker");
datePicker.max(new Date(parseInt(startDate[2]), parseInt(startDate[1]), parseInt(startDate[0])));
datePicker.value(new Date(parseInt(startDate[2]), parseInt(startDate[1]), parseInt(startDate[0])))
})
It doesnt works and i dont get an error. How can i do this? Thank you so much for you time.
I am using this:
KendoUI
JavaScript
ASP .NET MVC
RAZOR
jquery
you can use it in Jquery
function startChange() {
var endPicker = $("#dtpStartDate").data("kendoDatePicker"),
startDate = this.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
endPicker.max(startDate + 30);
}
}
function endChange() {
var startPicker = $("#dtpEndDate").data("kendoDatePicker"),
endDate = this.value();
if (endDate) {
endDate = new Date(endDate);
endDate.setDate(endDate.getDate());
startPicker.max(endDate - 30);
}
}
and in razor files you can create datepickers like this
<div class="form-group">
<label class="col-md-4 control-label">#Html.LabelFor(m => m.StartDate)</label>
<div class="col-md-8">
#(Html.Kendo().DatePickerFor(m => m.StartDate)
.HtmlAttributes(new { #Id = "dtpStartDate", style = "width:100%", required = "required", validationMessage = "Select Start Date" })
.Events(e => e.Change("startChange")))
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">#Html.LabelFor(m => m.EndDate)</label>
<div class="col-md-8">
#(Html.Kendo().DatePickerFor(m => m.EndDate)
.HtmlAttributes(new { #Id = "dtpEndDate", style = "width:100%", required = "required", validationMessage = "Select End Date" })
.Events(e=>e.Change("endChange")))
</div>
</div>

Can't pass value from input field daterangepicker - Zeppelin Angular

I have 2 input form fields that use daterangepicker to get single timestamps, I want to pass these to another paragraph after a button is clicked.
This is what the script looks like in para 1,
<label class = "name">From Date : </label>
<input type="text" id="fromDate" class = "dates" placeholder = "Select timestamp" ng-model="fromTs"></input>
<label class = "name">To Date : </label>
<input type="text" id="toDate" class = "dates" placeholder = "Select timestamp" ng-model="toTs"></input>
<script>
$(function() {
var start = moment();
var end = moment();
$('#fromDate').daterangepicker({
timePicker: true,
startDate: start,
singleDatePicker: true,
showDropdowns: true,
timePickerSeconds: true,
timePicker24Hour: true,
locale: {
format: 'DD-MM-YYYY HH:mm:ss'
}
});
$('#toDate').daterangepicker({
endDate: end,
timePicker: true,
singleDatePicker: true,
showDropdowns: true,
timePickerSeconds: true,
timePicker24Hour: true,
locale: {
format: 'DD-MM-YYYY HH:mm:ss'
}
});
});
</script>
<button type="submit" class="btnbtn-primary" ng-click="z.angularBind( 'fromTs', fromDate, 'paragraph_1590566438633_806469898'); z.angularBind('toTs', toTs, 'paragraph_1590566438633_806469898'); z.runParagraph( 'paragraph_1590566438633_806469898');">Apply</button>
And this is in para2,
%md
### Date range is ${fromTs} to ${toTS}
I get Nullpointer exception when I run this, checked in the console that there is no object being passed in case of fromTs and toTs.
Initially I was using bootstrap-datepicker but later moved to daterangepicker as it had the option of selection of time as well, using the ng-model value to pass the input field value worked there, but it doesn't seem to be working with daterangepicker.
Why is this happening and how do I go about this error?

Validation error 'getMonth' of null

I am using bootstrap validation for "Validating start and end datetimes".
Whenever I am trying to select start date from date-picker, I am finding error on console
Uncaught TypeError: Cannot read property 'getMonth' of null
mm # form_Validation.js:11(anonymous function) # form_Validation.js:11_formatDate # form_Validation.js:11validate #
form_Validation.js:11validateField # form_Validation.js:10revalidateField #
form_Validation.js:11(anonymous function) # form_Validation.js:11each # jquery.min.js:2each # jquery.min.js:2a.fn.formValidation #
form_Validation.js:11(anonymous function) # index1.php:658dispatch #
jquery.min.js:3r.handle # jquery.min.js:3trigger # jquery.min.js:3(anonymous
function) # jquery.min.js:3each # jquery.min.js:2each # jquery.min.js:2trigger
# jquery.min.js:3_trigger # bootstrap-datepicker.min.js:1_setDate # bootstrap-datepicker.min.js:1click # bootstrap-datepicker.min.js:1d #
jquery.min.js:2dispatch # jquery.min.js:3r.handle # jquery.min.js:3
The error is coming from line no. 11 of formValidation.min.js that is
g=f.getFullYear(),h=f.getMonth(),i=f.getDate();return g>a||a===g&&h>b-1||a===g&&b-1===h&&i>c}return!0},format:function(b,c){a.isArray(c)||(c=[c]);for(var d in c)b=b.replace("%s",c[d]);return b},luhn:function(a){for(var b=a.length,c=0,d=[[0,1,2,3,4,5,6,7,8,9],[0,2,4,6,8,1,3,5,7,9]],e=0;b--;)e+=d[c][parseInt(a.charAt(b),10)],c^=1;return e%10===0&&e>0},mod11And10:function(a){for(var b=5,c=a.length,d=0;c>d;d++)b=(2*(b||10)%11+parseInt(a.charAt(d),10))%10;return 1===b},mod37And36:function(a,b){b=b||"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";for(var c=b.length,d=a.length,e=Math.floor(c/2),f=0;d>f;f++)e=(2*(e||c)%(c+1)+b.indexOf(a.charAt(f)))%c;return 1===e}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{base64:{"default":"Please enter a valid base 64 encoded"}}}),FormValidation.Validator.base64={validate:function(a,b,c,d){var e=a.getFieldValue(b,d);return""===e?!0:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(e)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{between:{"default":"Please enter a value between %s and %s",notInclusive:"Please enter a value between %s and %s strictly"}}}),FormValidation.Validator.between={html5Attributes:{message:"message",min:"min",max:"max",inclusive:"inclusive"},enableByHtml5:function(a){return"range"===a.attr("type")?{min:a.attr("min"),max:a.attr("max")}:!1},validate:function(b,c,d,e){var f=b.getFieldValue(c,e);if(""===f)return!0;f=this._format(f);var g=b.getLocale(),h=a.isNumeric(d.min)?d.min:b.getDynamicOption(c,d.min),i=a.isNumeric(d.max)?d.max:b.getDynamicOption(c,d.max),j=this._format(h),k=this._format(i);return d.inclusive===!0||void 0===d.inclusive?{valid:a.isNumeric(f)&&parseFloat(f)>=j&&parseFloat(f)<=k,message:FormValidation.Helper.format(d.message||FormValidation.I18n[g].between["default"],[h,i])}:{valid:a.isNumeric(f)&&parseFloat(f)>j&&parseFloat(f)<k,message:FormValidation.Helper.format(d.message||FormValidation.I18n[g].between.notInclusive,[h,i])}},_format:function(a){return(a+"").replace(",",".")}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{bic:{"default":"Please enter a valid BIC number"}}}),FormValidation.Validator.bic={validate:function(a,b,c,d){var e=a.getFieldValue(b,d);return""===e?!0:/^[a-zA-Z]{6}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?$/.test(e)}}}(jQuery),function(a){FormValidation.Validator.blank={validate:function(a,b,c,d){return!0}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{callback:{"default":"Please enter a valid value"}}}),FormValidation.Validator.callback={priority:999,html5Attributes:{message:"message",callback:"callback"},validate:function(b,c,d,e){var f=b.getFieldValue(c,e),g=new a.Deferred,h={valid:!0};if(d.callback){var i=FormValidation.Helper.call(d.callback,[f,b,c]);h="boolean"==typeof i||null===i?{valid:i}:i}return g.resolve(c,e,h),g}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{choice:{"default":"Please enter a valid value",less:"Please choose %s options at minimum",more:"Please choose %s options at maximum",between:"Please choose %s - %s options"}}}),FormValidation.Validator.choice={html5Attributes:{message:"message",min:"min",max:"max"},validate:function(b,c,d,e){var f=b.getLocale(),g=b.getNamespace(),h=c.is("select")?b.getFieldElements(c.attr("data-"+g+"-field")).find("option").filter(":selected").length:b.getFieldElements(c.attr("data-"+g+"-field")).filter(":checked").length,i=d.min?a.isNumeric(d.min)?d.min:b.getDynamicOption(c,d.min):null,j=d.max?a.isNumeric(d.max)?d.max:b.getDynamicOption(c,d.max):null,k=!0,l=d.message||FormValidation.I18n[f].choice["default"];switch((i&&h<parseInt(i,10)||j&&h>parseInt(j,10))&&(k=!1),!0){case!!i&&!!j:l=FormValidation.Helper.format(d.message||FormValidation.I18n[f].choice.between,[parseInt(i,10),parseInt(j,10)]);break;case!!i:l=FormValidation.Helper.format(d.message||FormValidation.I18n[f].choice.less,parseInt(i,10));break;case!!j:l=FormValidation.Helper.format(d.message||FormValidation.I18n[f].choice.more,parseInt(j,10))}return{valid:k,message:l}}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{color:{"default":"Please enter a valid color"}}}),FormValidation.Validator.color={html5Attributes:{message:"message",type:"type"},enableByHtml5:function(a){return"color"===a.attr("type")},SUPPORTED_TYPES:["hex","rgb","rgba","hsl","hsla","keyword"],KEYWORD_COLORS:["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","transparent","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"],validate:function(b,c,d,e){var f=b.getFieldValue(c,e);if(""===f)return!0;if(this.enableByHtml5(c))return/^#[0-9A-F]{6}$/i.test(f);var g=d.type||this.SUPPORTED_TYPES;a.isArray(g)||(g=g.replace(/s/g,"").split(","));for(var h,i,j=!1,k=0;k<g.length;k++)if(i=g[k],h="_"+i.toLowerCase(),j=j||this[h](f))return!0;return!1},_hex:function(a){return/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(a)},_hsl:function(a){return/^hsl\((\s*(-?\d+)\s*,)(\s*(\b(0?\d{1,2}|100)\b%)\s*,)(\s*(\b(0?\d{1,2}|100)\b%)\s*)\)$/.test(a)},_hsla:function(a){return/^hsla\((\s*(-?\d+)\s*,)(\s*(\b(0?\d{1,2}|100)\b%)\s*,){2}(\s*(0?(\.\d+)?|1(\.0+)?)\s*)\)$/.test(a)},_keyword:function(b){return a.inArray(b,this.KEYWORD_COLORS)>=0},_rgb:function(a){var b=/^rgb\((\s*(\b([01]?\d{1,2}|2[0-4]\d|25[0-5])\b)\s*,){2}(\s*(\b([01]?\d{1,2}|2[0-4]\d|25[0-5])\b)\s*)\)$/,c=/^rgb\((\s*(\b(0?\d{1,2}|100)\b%)\s*,){2}(\s*(\b(0?\d{1,2}|100)\b%)\s*)\)$/;return b.test(a)||c.test(a)},_rgba:function(a){var b=/^rgba\((\s*(\b([01]?\d{1,2}|2[0-4]\d|25[0-5])\b)\s*,){3}(\s*(0?(\.\d+)?|1(\.0+)?)\s*)\)$/,c=/^rgba\((\s*(\b(0?\d{1,2}|100)\b%)\s*,){3}(\s*(0?(\.\d+)?|1(\.0+)?)\s*)\)$/;return b.test(a)||c.test(a)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{creditCard:{"default":"Please enter a valid credit card number"}}}),FormValidation.Validator.creditCard={validate:function(b,c,d,e){var f=b.getFieldValue(c,e);if(""===f)return!0;if(/[^0-9-\s]+/.test(f))return!1;if(f=f.replace(/\D/g,""),!FormValidation.Helper.luhn(f))return!1;var g,h,i={AMERICAN_EXPRESS:{length:[15],prefix:["34","37"]},DINERS_CLUB:{length:[14],prefix:["300","301","302","303","304","305","36"]},DINERS_CLUB_US:{length:[16],prefix:["54","55"]},DISCOVER:{length:[16],prefix:["6011","622126","622127","622128","622129","62213","62214","62215","62216","62217","62218","62219","6222","6223","6224","6225","6226","6227","6228","62290","62291","622920","622921","622922","622923","622924","622925","644","645","646","647","648","649","65"]},JCB:{length:[16],prefix:["3528","3529","353","354","355","356","357","358"]},LASER:{length:[16,17,18,19],prefix:["6304","6706","6771","6709"]},MAESTRO:{length:[12,13,14,15,16,17,18,19],prefix:["5018","5020","5038","6304","6759","6761","6762","6763","6764","6765","6766"]},MASTERCARD:{length:[16],prefix:["51","52","53","54","55"]},SOLO:{length:[16,18,19],prefix:["6334","6767"]},UNIONPAY:{length:[16,17,18,19],prefix:["622126","622127","622128","622129","62213","62214","62215","62216","62217","62218","62219","6222","6223","6224","6225","6226","6227","6228","62290","62291","622920","622921","622922","622923","622924","622925"]},VISA:{length:[16],prefix:["4"]}};for(g in i)for(h in i[g].prefix)if(f.substr(0,i[g].prefix[h].length)===i[g].prefix[h]&&-1!==a.inArray(f.length,i[g].length))return{valid:!0,type:g};return!1}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{cusip:{"default":"Please enter a valid CUSIP number"}}}),FormValidation.Validator.cusip={validate:function(b,c,d,e){var f=b.getFieldValue(c,e);if(""===f)return!0;if(f=f.toUpperCase(),!/^[0-9A-Z]{9}$/.test(f))return!1;for(var g=a.map(f.split(""),function(a){var b=a.charCodeAt(0);return b>="A".charCodeAt(0)&&b<="Z".charCodeAt(0)?b-"A".charCodeAt(0)+10:a}),h=g.length,i=0,j=0;h-1>j;j++){var k=parseInt(g[j],10);j%2!==0&&(k*=2),k>9&&(k-=9),i+=k}return i=(10-i%10)%10,i===parseInt(g[h-1],10)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{cvv:{"default":"Please enter a valid CVV number"}}}),FormValidation.Validator.cvv={html5Attributes:{message:"message",ccfield:"creditCardField"},init:function(a,b,c,d){if(c.creditCardField){var e=a.getFieldElements(c.creditCardField);a.onLiveChange(e,"live_"+d,function(){var c=a.getStatus(b,d);c!==a.STATUS_NOT_VALIDATED&&a.revalidateField(b)})}},destroy:function(a,b,c,d){if(c.creditCardField){var e=a.getFieldElements(c.creditCardField);a.offLiveChange(e,"live_"+d)}},validate:function(b,c,d,e){var f=b.getFieldValue(c,e);if(""===f)return!0;if(!/^[0-9]{3,4}$/.test(f))return!1;if(!d.creditCardField)return!0;var g=b.getFieldElements(d.creditCardField).val();if(""===g)return!0;g=g.replace(/\D/g,"");var h,i,j={AMERICAN_EXPRESS:{length:[15],prefix:["34","37"]},DINERS_CLUB:{length:[14],prefix:["300","301","302","303","304","305","36"]},DINERS_CLUB_US:{length:[16],prefix:["54","55"]},DISCOVER:{length:[16],prefix:["6011","622126","622127","622128","622129","62213","62214","62215","62216","62217","62218","62219","6222","6223","6224","6225","6226","6227","6228","62290","62291","622920","622921","622922","622923","622924","622925","644","645","646","647","648","649","65"]},JCB:{length:[16],prefix:["3528","3529","353","354","355","356","357","358"]},LASER:{length:[16,17,18,19],prefix:["6304","6706","6771","6709"]},MAESTRO:{length:[12,13,14,15,16,17,18,19],prefix:["5018","5020","5038","6304","6759","6761","6762","6763","6764","6765","6766"]},MASTERCARD:{length:[16],prefix:["51","52","53","54","55"]},SOLO:{length:[16,18,19],prefix:["6334","6767"]},UNIONPAY:{length:[16,17,18,19],prefix:["622126","622127","622128","622129","62213","62214","62215","62216","62217","62218","62219","6222","6223","6224","6225","6226","6227","6228","62290","62291","622920","622921","622922","622923","622924","622925"]},VISA:{length:[16],prefix:["4"]}},k=null;for(h in j)for(i in j[h].prefix)if(g.substr(0,j[h].prefix[i].length)===j[h].prefix[i]&&-1!==a.inArray(g.length,j[h].length)){k=h;break}return null===k?!1:"AMERICAN_EXPRESS"===k?4===f.length:3===f.length}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{date:{"default":"Please enter a valid date",min:"Please enter a date after %s",max:"Please enter a date before %s",range:"Please enter a date in the range %s - %s"}}}),FormValidation.Validator.date={html5Attributes:{message:"message",format:"format",min:"min",max:"max",separator:"separator"},validate:function(b,c,d,e){var f=b.getFieldValue(c,e);if(""===f)return!0;d.format=d.format||"MM/DD/YYYY","date"===c.attr("type")&&(d.format="YYYY-MM-DD");var g=b.getLocale(),h=d.message||FormValidation.I18n[g].date["default"],i=d.format.split(" "),j=i[0],k=i.length>1?i[1]:null,l=i.length>2?i[2]:null,m=f.split(" "),n=m[0],o=m.length>1?m[1]:null;if(i.length!==m.length)return{valid:!1,message:h};var p=d.separator;if(p||(p=-1!==n.indexOf("/")?"/":-1!==n.indexOf("-")?"-":-1!==n.indexOf(".")?".":null),null===p||-1===n.indexOf(p))return{valid:!1,message:h};if(n=n.split(p),j=j.split(p),n.length!==j.length)return{valid:!1,message:h};var q=n[a.inArray("YYYY",j)],r=n[a.inArray("MM",j)],s=n[a.inArray("DD",j)];if(!q||!r||!s||4!==q.length)return{valid:!1,message:h};var t=null,u=null,v=null;if(k){if(k=k.split(":"),o=o.split(":"),k.length!==o.length)return{valid:!1,message:h};if(u=o.length>0?o[0]:null,t=o.length>1?o[1]:null,v=o.length>2?o[2]:null,""===u||""===t||""===v)return{valid:!1,message:h};if(v){if(isNaN(v)||v.length>2)return{valid:!1,message:h};if(v=parseInt(v,10),0>v||v>60)return{valid:!1,message:h}}if(u){if(isNaN(u)||u.length>2)return{valid:!1,message:h};if(u=parseInt(u,10),0>u||u>=24||l&&u>12)return{valid:!1,message:h}}if(t){if(isNaN(t)||t.length>2)return{valid:!1,message:h};if(t=parseInt(t,10),0>t||t>59)return{valid:!1,message:h}}}var w=FormValidation.Helper.date(q,r,s),x=null,y=null,z=d.min,A=d.max;switch(z&&(x=z instanceof Date?z:this._parseDate(z,j,p)||this._parseDate(b.getDynamicOption(c,z),j,p),z=this._formatDate(x,d.format)),A&&(y=A instanceof Date?A:this._parseDate(A,j,p)||this._parseDate(b.getDynamicOption(c,A),j,p),A=this._formatDate(y,d.format)),n=new Date(q,r-1,s,u,t,v),!0){case z&&!A&&w:w=n.getTime()>=x.getTime(),h=d.message||FormValidation.Helper.format(FormValidation.I18n[g].date.min,z);break;case A&&!z&&w:w=n.getTime()<=y.getTime(),h=d.message||FormValidation.Helper.format(FormValidation.I18n[g].date.max,A);break;case A&&z&&w:w=n.getTime()<=y.getTime()&&n.getTime()>=x.getTime(),h=d.message||FormValidation.Helper.format(FormValidation.I18n[g].date.range,[z,A])}return{valid:w,date:n,message:h}},_parseDate:function(b,c,d){if(b instanceof Date)return b;if("string"!=typeof b)return null;var e=a.inArray("YYYY",c),f=a.inArray("MM",c),g=a.inArray("DD",c);if(-1===e||-1===f||-1===g)return null;var h=0,i=0,j=0,k=b.split(" "),l=k[0].split(d);if(l.length<3)return null;if(k.length>1){var m=k[1].split(":");i=m.length>0?m[0]:null,h=m.length>1?m[1]:null,j=m.length>2?m[2]:null}return new Date(l[e],l[f]-1,l[g],i,h,j)},_formatDate:function(a,b){b=b.replace(/Y/g,"y").replace(/M/g,"m").replace(/D/g,"d").replace(/:m/g,":M").replace(/:mm/g,":MM").replace(/:S/,":s").replace(/:SS/,":ss");var c={d:function(a){return a.getDate()},dd:function(a){var b=a.getDate();return 10>b?"0"+b:b},m:function(a){return a.getMonth()+1},mm:function(a){var b=a.getMonth()+1;return 10>b?"0"+b:b},yy:function(a){return(""+a.getFullYear()).substr(2)},yyyy:function(a){return a.getFullYear()},h:function(a){return a.getHours()%12||12},hh:function(a){var b=a.getHours()%12||12;return 10>b?"0"+b:b},H:function(a){return a.getHours()},HH:function(a){var b=a.getHours();return 10>b?"0"+b:b},M:function(a){return a.getMinutes()},MM:function(a){var b=a.getMinutes();return 10>b?"0"+b:b},s:function(a){return a.getSeconds()},ss:function(a){var b=a.getSeconds();return 10>b?"0"+b:b}};return b.replace(/d{1,4}|m{1,4}|yy(?:yy)?|([HhMs])\1?|"[^"]*"|'[^']*'/g,function(b){return c[b]?c[b](a):b.slice(1,b.length-1)})}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{different:{"default":"Please enter a different value"}}}),FormValidation.Validator.different={html5Attributes:{message:"message",field:"field"},init:function(b,c,d,e){for(var f=d.field.split(","),g=0;g<f.length;g++){var h=b.getFieldElements(a.trim(f[g]));b.onLiveChange(h,"live_"+e,function(){var a=b.getStatus(c,e);a!==b.STATUS_NOT_VALIDATED&&b.revalidateField(c)})}},destroy:function(b,c,d,e){for(var f=d.field.split(","),g=0;g<f.length;g++){var h=b.getFieldElements(a.trim(f[g]));b.offLiveChange(h,"live_"+e)}},validate:function(b,c,d,e){var f=b.getFieldValue(c,e);if(""===f)return!0;for(var g=d.field.split(","),h=!0,i=0;i<g.length;i++){var j=b.getFieldElements(a.trim(g[i]));if(null!=j&&0!==j.length){var k=b.getFieldValue(j,e);f===k?h=!1:""!==k&&b.updateStatus(j,b.STATUS_VALID,e)}}return h}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{digits:{"default":"Please enter only digits"}}}),FormValidation.Validator.digits={validate:function(a,b,c,d){var e=a.getFieldValue(b,d);return""===e?!0:/^\d+$/.test(e)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{ean:{"default":"Please enter a valid EAN number"}}}),FormValidation.Validator.ean={validate:function(a,b,c,d){var e=a.getFieldValue(b,d);if(""===e)return!0;if(!/^(\d{8}|\d{12}|\d{13})$/.test(e))return!1;for(var f=e.length,g=0,h=8===f?[3,1]:[1,3],i=0;f-1>i;i++)g+=parseInt(e.charAt(i),10)*h[i%2];return g=(10-g%10)%10,g+""===e.charAt(f-1)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{ein:{"default":"Please enter a valid EIN number"}}}),FormValidation.Validator.ein={CAMPUS:{ANDOVER:["10","12"],ATLANTA:["60","67"],AUSTIN:["50","53"],BROOKHAVEN:["01","02","03","04","05","06","11","13","14","16","21","22","23","25","34","51","52","54","55","56","57","58","59","65"],CINCINNATI:["30","32","35","36","37","38","61"],FRESNO:["15","24"],KANSAS_CITY:["40","44"],MEMPHIS:["94","95"],OGDEN:["80","90"],PHILADELPHIA:["33","39","41","42","43","48","62","63","64","66","68","71","72","73","74","75","76","77","81","82","83","84","85","86","87","88","91","92","93","98","99"],INTERNET:["20","26","27","45","46","47"],SMALL_BUSINESS_ADMINISTRATION:["31"]},validate:function(b,c,d,e){var f=b.getFieldValue(c,e);if(""===f)return!0;if(!/^[0-9]{2}-?[0-9]{7}$/.test(f))return!1;var g=f.substr(0,2)+"";for(var h in this.CAMPUS)if(-1!==a.inArray(g,this.CAMPUS[h]))return{valid:!0,campus:h};return!1}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{emailAddress:{"default":"Please enter a valid email address"}}}),FormValidation.Validator.emailAddress={html5Attributes:{message:"message",multiple:"multiple",separator:"separator"},enableByHtml5:function(a){return"email"===a.attr("type")},validate:function(a,b,c,d){var e=a.getFieldValue(b,d);if(""===e)return!0;var f=/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,g=c.multiple===!0||"true"===c.multiple;if(g){for(var h=c.separator||/[,;]/,i=this._splitEmailAddresses(e,h),j=0;j<i.length;j++)if(!f.test(i[j]))return!1;return!0}return f.test(e)},_splitEmailAddresses:function(a,b){for(var c=a.split(/"/),d=c.length,e=[],f="",g=0;d>g;g++)if(g%2===0){var h=c[g].split(b),i=h.length;if(1===i)f+=h[0];else{e.push(f+h[0]);for(var j=1;i-1>j;j++)e.push(h[j]);f=h[i-1]}}else f+='"'+c[g],d-1>g&&(f+='"');return e.push(f),e}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{file:{"default":"Please choose a valid file"}}}),FormValidation.Validator.file={html5Attributes:{extension:"extension",maxfiles:"maxFiles",minfiles:"minFiles",maxsize:"maxSize"",
Is anyone there to sort out this error?
HTML:
<div class="form-group">
<label for="rpassword" class="col-sm-2 control-label">
Departure Date
</label>
<div class="col-xs-5 dateContainer">
<div class="col-sm-10 input-group input-append date" id="startDatePicker">
<input type="text" id="depDate" name="depDate" class="form-control" placeholder="Enter Departure Date">
<span class="input-group-addon add-on"><span class="glyphicon glyphicon-calendar"></span></span>
</div>
</div>
</div>
JS Validation Code:
$(document).ready(function() {
$('#startDatePicker')
.datepicker({
format: 'mm/dd/yyyy'
})
.on('changeDate', function(e) {
// Revalidate the start date field
$('#eventForm').formValidation('revalidateField', 'depDate');
});
$('#endDatePicker')
.datepicker({
format: 'mm/dd/yyyy'
})
.on('changeDate', function(e) {
$('#eventForm').formValidation('revalidateField', 'retDate');
});
$('#eventForm')
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
depDate: {
validators: {
notEmpty: {
message: 'The start date is required'
},
date: {
format: 'MM/DD/YYYY',
max: 'endDate',
message: 'The start date is not a valid'
}
}
},
retDate: {
validators: {
notEmpty: {
message: 'The end date is required'
},
date: {
format: 'MM/DD/YYYY',
min: 'startDate',
message: 'The end date is not a valid'
}
}
}
}
})
.on('success.field.fv', function(e, data) {
if (data.field === 'depDate' && !data.fv.isValidField('retDate')) {
// We need to revalidate the end date
data.fv.revalidateField('retDate');
}
if (data.field === 'retDate' && !data.fv.isValidField('depDate')) {
// We need to revalidate the start date
data.fv.revalidateField('depDate');
}
});
});
</script>

extend mean module findOne() to handle other attributes that strings

When start a new meanjs project (mongoose, angular etc.) using the generator and add a CRUD-module i get methods like this:
$scope.findOne = function() {
$scope.income = Incomes.get({
incomeId: $stateParams.incomeId
});
In my income server model is shown below, it has some different attributes and some different object types on these attributes, for example, number, date and string.
When i get data in my $scope.income after the promise "$scope.findOne" has succeded all my data are strings. Do i need to cast each and every one of them to their proper type?
In my front end i want to present the different types in the input elements of my "update" view. For example:
<label class="control-label" for="date">Date of transaction</label>
<div class="list-group-item">
<div class="controls">
<input type="date" data-ng-model="income.date" id="date" class="form-control" placeholder="Date" required>
</div>
This does not work since the object $scope.income.date consists of a string. Changing the input type to string makes it show up. But I want to use a date picker here.
Should I write something like:
$scope.findOne = function() {
Incomes.get({
incomeId: $stateParams.incomeId
}).then(function(data){
var dateVar=new Date(data.date);
var amountVar =Number(data.amount)
$scope.income ={date: dateVar, name: data.name, amount:amountVar}()
);
What is best practise here?
Model I am using:
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Income Schema
*/
var IncomeSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Income name',
trim: true
},
amount: {
type: String,
default: '',
required: 'Please fill Income amount',
trim: true
},
date: {
type: Date,
default: '',
required: 'Please fill Income date',
trim: true
},
monthly: {
type: Boolean,
default: '',
required: 'Please fill whether income is recurring monthly',
trim: true
},
yearly: {
type: Boolean,
default: '',
required: 'Please fill whether income is recurring yearly',
trim: true
},
account: {
type: Schema.ObjectId,
ref: 'Account',
required: 'Please select account'
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Income', IncomeSchema);
First I had to get a hold of the promise, than I easily could build more complex objects from the Incomes.get response. The data is sent over the network as JSON and there fore it is just text, so I needed to instantiate it to the proper types using f ex. Date and Number:
Incomes.get({
incomeId: $stateParams.incomeId
}).$promise.then(function(data){
var dateVar=new Date(data.date);
var amountVar =Number(data.amount)
$scope.income ={date: dateVar, name: data.name, amount:amountVar}()
);
To make the resources function for remove work properly "this" needed to be used, dont forget that the promise is in another namespace so "that=this" is needed.
var that=this;
Incomes.get({
incomeId: $stateParams.incomeId
}).$promise.then(function(income){
income.date= new Date(income.date);
var recurringVar;
if(income.monthly===true){
recurringVar = 'monthly';
} else if( income.yearly===true){
recurringVar = 'yearly';
}
income.recurring=recurringVar;
that.income=income;
});

Categories

Resources