如何验证文本输入字段接收日期,使其从今天起在 4 到 8 周之间?



我有几个输入字段。而且,我正在使用jQuery验证插件验证这些字段,可以从这里找到:https://jqueryvalidation.org/

我可以验证输入文本字段和接收日期值的输入文本字段。但是,我需要确保收到的日期从今天起 4 到 8 周之间。怎么做?

.HTML:

<form>
Name: <input type="text" maxlength="50" class="nf-givenname"><br/> <br/> 
date that does not work: 
<input type="text" maxlength="45" class="nf-date-picker" name="Date">
<br/> <br/> 
<input type="submit" value="Submit" class="btn-save date"  commandtype="Save">
</form>

而且,到目前为止,jQuery代码对我来说如下所示:

$(document).ready(function() {
var $form = $("form");
$form.validate({
submitHandler: function() {
//
}
});
// Ensures the classNames associated with the form elements can be used for validation
$.validator.addClassRules = function(className, rules) {
if (className.constructor === String) {
var obj = {};
obj[className] = rules;
className = obj;
}
$.each(className, function(n, r) {
$("." + n).each(function(i, e) {
var self = $(e);
self.rules("add", r);
});
});
};
$.validator.addMethod(
"dateRange",
function(value, element, params) {
console.log("value is" + value);
try {
console.log(
"Entered value is" +
value +
" params.from  is" +
params.from +
" param to is" +
params.to
);
if (value > params.from && value < params.to) {
return true;
}
} catch (e) {}
return false;
},
"Please enter date within range (4 to 8 weeks)"
);
var formattedDate = new Date()
.toJSON()
.slice(0, 10)
.split("-")
.reverse()
.join("-"),
dateTokens = formattedDate.split("-"),
dt = new Date(dateTokens[2], parseInt(dateTokens[1], 10) - 1, dateTokens[0]), // months are 0 based, so need to add 1
inFourWeeks = new Date(dt.getTime() + 28 * 24 * 60 * 60 * 1000)
.toJSON()
.slice(0, 10)
.split("-")
.reverse()
.join("-"),
inEightWeeks = new Date(dt.getTime() + 56 * 24 * 60 * 60 * 1000)
.toJSON()
.slice(0, 10)
.split("-")
.reverse()
.join("-");
var fromDate = inFourWeeks;
var toDate = inEightWeeks;
$(".nf-date-picker").addClass("myDateFieldRangeValidate");
$.validator.addClassRules({
myDateFieldRangeValidate: {
dateRange: {
from: fromDate,
to: toDate
}
},
"nf-givenname": {
required: true,
messages: {
required: "Please specify your given (first) name"
}
},
"nf-date-picker": {
required: true,
messages: {
required: "Please choose a date"
}
}
});
});

我创造了一支笔来展示我目前正在挣扎的东西。作品代码笔链接如下: https://codepen.io/hellouniverse/pen/aGjoKw?editors=1012

问题是messages属性,addClassRules()方法似乎并不完全支持该属性。我不知道这对您来说是否是一个可行的替代方案,但我将您的规则对象保存到var rules并循环它以将类名设置为name属性。这样,您可以默认方式添加规则。这是您的选择吗?

编辑:我为默认日期检查添加了自定义验证方法。它会验证输入的日期是否在 4 到 8 周之间。日期格式设置为dd/mm/yyyy。这应该让你开始...

var $form = $("form");

var rules = {
"nf-givenname": {
		    required: true,
messages: {
required: "Please specify your given (first) name"
	      }
		},
		"nf-date-picker": {
			  required: true,
			  date: true
//dateISO: true
		},
		"txt_dob": {
		    required: true
		}
};

$form.validate({
submitHandler: function(form) {
//
		}
});
// Date format is dd/mm/yyyy for the validation!
$.validator.methods.date = function(value, element) {
var dates = {
"today": new Date(),
"four_weeks": new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 28)),
"eight_weeks": new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 56))
};


for (var k in dates) {
if (dates.hasOwnProperty(k)) {
var dd = dates[k].getDate();
var mm = dates[k].getMonth()+1;

if (dd < 10) dd = '0' + dd;
if (mm < 10) mm = '0' + mm;

dates[k] = dd + '/' + mm + '/' + dates[k].getFullYear();
}
}
var date_from = dates["four_weeks"].split("/");
var date_to = dates["eight_weeks"].split("/");
var val =  value.split("/");
var from = new Date(
date_from[2],
parseInt(date_from[1])-1, date_from[0]
);

var to = new Date(
date_to[2],
parseInt(date_to[1])-1, date_to[0]
);

var check = new Date(
val[2],
parseInt(val[1])-1, val[0]
);
return this.optional(element) || (check > from && check < to);
}

//------ Only for this test to prevent snippet reload.
$form.on('submit', function(e){
e.preventDefault();
});
//------ 


for (var k in rules) {
if (rules.hasOwnProperty(k)) {
$('.' + k).attr('name', k).rules('add', rules[k]);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>
<form>
	Name: 
<input type="text" maxlength="50" class="nf-givenname">
<br/> <br/> 
	date that does not work:
	<input type="text" maxlength="45" class="nf-date-picker hasDatepicker">
	<br/> <br/> 
	date that does  work: 
	<input type="text" class="txt_dob" name="loreumipsum" />
	
	<input type="submit" value="Submit" class="btn-save date"  commandtype="Save">
</form>

相关内容

  • 没有找到相关文章

最新更新