$(function () {
$.datepicker.setDefaults({
dateFormat: 'dd/mm/yy'
});
});
Then to bind it to the input element:
$(function () {
$("#StartDate").datepicker();
});
Credits Amalea
Pergunta
I am having real trouble with this addMethod for validating a date from an input. It doesn't test the regex properly and i think it may be written with errors. The date should be in this format: dd.mm.yyyy . Please help...
$(function() {
$(".msgBtn").click(function() {
var isValid = true;
if (!$("#startDate").valid()) {
isValid = false;
}
if (!$("#endDate").valid()) {
isValid = false;
}
if (!isValid)
return;
$("form#csr-message").submit(); //save button
});
});
$.validator.addMethod(
"formatdata",
function(value, element) {
var i = /(?:0[1-9]|[12][0-9]|3[01])\.(?:0[1-9]|1[0-2])\.(?:19\d\d|20\d\d)/;
return this.optional(element) || i.test(value);
}, "Incorrect format data");
var validator = $("#csr-message")
.validate(
{
rules : {
startDate : {
formatdata : true
},
endDate : {
formatdata : true
}
},
messages : {
startDate : {
formatdata : jQuery
.format("Start date has incorrect format!"),
},
endDate : {
formatdata : jQuery
.format("End date has incorrect format!"),
}
}
}
The html:
<form method="post" action="<%=RelativeActionURL.rewrite(formAction)%>" id="csr-message">
...
<input type="text" id="startDate" name="startDate" placeholder="dd.mm.yyyy" value="<fmt:formatDate pattern="dd.MM.yyyy" value="${messageDetails.startDate}" />"/>
...
<input type="text" id="endDate" name="endDate" placeholder="dd.mm.yyyy" value="<fmt:formatDate pattern="dd.MM.yyyy" value="${messageDetails.endDate}"/>"/>
...
</form>
Solução 2
$(function () {
$.datepicker.setDefaults({
dateFormat: 'dd/mm/yy'
});
});
Then to bind it to the input element:
$(function () {
$("#StartDate").datepicker();
});
Credits Amalea
Outras dicas
You can create your own custom validation method using the addMethod function. Say you wanted to validate "dd/mm/yyyy":
$.validator.addMethod(
"Mytypedate",
function(value, element) {
// put your own logic here, this is just a (crappy) example
return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
},
"Please enter a date in the format dd/mm/yyyy."
);
And then on your form add:
$('#myForm')
.validate({
rules : {
myDate : {
Mytypedate: true
}
}
})
;