How can I specify a custom date formate to be validated with the Validation Plugin for jQuery?
thanks!
How can I specify a custom date formate to be validated with the Validation Plugin for jQuery?
thanks!
You can create your own custom validation method using the addMethod
function. Say you wanted to validate "dd/mm/yyyy":
$.validator.addMethod(
"australianDate",
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:
$('#myForm')
.validate({
rules :
myDate : {
australianDate : true
}
})
;
nickf's answer is good, but note that the validation plug-in already includes validators for several other date formats, in the additional-methods.js file. Before you write your own, make sure that someone hasn't already done it.
I am really struggling with what I am doing wrong here. I have copied and pasted this code from above in a test app and it does not execute. Perhaps someone can throw me a bone here?
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
Home Page
<script type="text/javascript">
$(document).ready(function() {
$.validator.addMethod(
"australianDate",
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"
);
$('#myForm')
.validate({
rules :
myDate : {
australianDate : true
}
})
;
});
</script>
<form id="testForm" method="get" action="">
<h2><%= Html.Encode(ViewData["Message"]) %></h2>
<label for="textBox1">Test Text:</label>
<br />
<%= Html.TextBox("textBox1") %>
<br />
<input type="submit" value="ok" />
</form>
Many thanks in advance.
Jon, you have some syntax errors, see below, this worked for me.
<script type="text/javascript">
$(document).ready(function () {
$.validator.addMethod(
"australianDate",
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"
);
$('#testForm').validate({
rules: {
"myDate": {
australianDate: true
}
}
});
});
@Chris: do you have for US date format (mm/dd/yyyy) please see my questions i have posted. http://stackoverflow.com/questions/2715626/jquery-datepicker-validate-date-mm-dd-yyyy
ps: i tried to write on comments but it says locked or deleted