我使用jquery创建了自定义验证,但我可以看到自己重复一些代码。任何人都可以帮我缩短下面的代码吗?
我正在寻找一种传递一些参数并在其他函数中重用一些代码的方法
非常感谢任何帮助
var errorslist = [];
function datevalidation(){
var day = $("#birthday-day").val();
var month = $("#birthday-month").val();
var year = $("#birthday-year").val();
var validday = new RegExp ("(^0?([1-9]?|[1][0-9]|[2][0-9]|[3][0-1])$)");
var validmonth = new RegExp ("(^0?([1-9]?|[1][0-2])$)");
var validyear = new RegExp ("((?!1900)(19[0-9]{2}|200[0-9]|201[0-3]))");
var date_error = $("#birthday-day").parent(".form-input").siblings(".form-info").children(".1stperror");
if(!(day.match(validday) && month.match(validmonth) && year.match(validyear))){
$(date_error).css("display","table-cell");
if($.inArray('date', errorslist)== -1){
errorslist.push('date');
}
}else{
$(date_error).css("display","none");
var index = $.inArray('date', errorslist);
if(index > -1){
errorslist.splice(index,1);
}
}
}
function adressvalidation(){
var checkadress = $("#adress").val();
var adress_error = $("#adress").parent(".form-input").siblings(".form-info").children(".1stperror");
if(checkadress==""){
$(adress_error).css("display","table-cell");
if($.inArray('adress', errorslist)== -1){
errorslist.push('adress');
}
}else{
$(adress_error).css("display","none");
var index = $.inArray('adress', errorslist);
if(index > -1){
errorslist.splice(index,1);
}
}
}
function cityvalidation(){
var checkcity = $("#city").val();
var city_error = $("#city").parent(".form-input").siblings(".form-info").children(".1stperror");
if(checkcity==""){
$(city_error).css("display","table-cell");
if($.inArray('city', errorslist)== -1){
errorslist.push('city');
}
}else{
$(city_error).css("display","none");
var index = $.inArray('city', errorslist);
if(index > -1){
errorslist.splice(index,1);
}
}
}
答案 0 :(得分:1)
为什么不去找jQuery form validator这样的第三方图书馆? 还有更多......
<!-- adress has two 'd' by the way: address -->
<input id="address" type="text" data-validation="length" data-validation-length="min10">
<input id="city" type="text" data-validation="length" data-validation-length="min10">
日期验证可以解决创建一个输入:
<input id="birthday" type="date" data-validation="date" data-validation-format="dd/mm/yyyy">