2016-07-08 9 views

risposta

4

È possibile utilizzare il validatore della data da Date-Module e aggiungere uno custom validator.

Ho appena aggiunto la riga var requiredAge = 18; e aggiunto la variabile alla convalida.

https://jsfiddle.net/03ehx9ns/

$.validate({ 
 
    modules : 'date' 
 
}); 
 

 
$.formUtils.addValidator({ 
 
    name : 'older18', 
 
    validatorFunction : function(val, $el, conf) { 
 
    \t var requiredAge = 18; 
 
    \t var dateFormat = 'yyyy-mm-dd'; 
 
    if($el.valAttr('format')) { 
 
     dateFormat = $el.valAttr('format'); 
 
    } 
 
    else if(typeof conf.dateFormat !== 'undefined') { 
 
     dateFormat = conf.dateFormat; 
 
    } 
 

 
    var inputDate = $.formUtils.parseDate(val, dateFormat); 
 
    if (!inputDate) { 
 
     return false; 
 
    } 
 

 
    var d = new Date(); 
 
    var currentYear = d.getFullYear(); 
 
    var year = inputDate[0]; 
 
    var month = inputDate[1]; 
 
    var day = inputDate[2]; 
 

 
    if (year === currentYear - requiredAge) { 
 
     var currentMonth = d.getMonth() + 1; 
 
     if (month === currentMonth) { 
 
     var currentDay = d.getDate(); 
 
     return day <= currentDay; 
 
     } 
 
     else { 
 
     return month < currentMonth; 
 
     } 
 
    } 
 
    else { 
 
     return year < currentYear - requiredAge && year > (currentYear - 124); // we can not live for ever yet... 
 
    } 
 
    }, 
 
    errorMessage : 'You need to be older then 18', 
 
    errorMessageKey: 'badDate' 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script> 
 

 
<form action="" id="date-form"> 
 
    <p> 
 
     Birth date 
 
     <input name="..." data-validation="older18" 
 
\t \t data-validation-help="yyyy-mm-dd (Not allowing dates in..."> 
 
    </p> 
 
    <p> 
 
     Time 
 
     <input name="" data-validation="time" data-validation-help="HH:mm"> 
 
    </p> 
 
    <p> 
 
     <input type="submit"> 
 
    </p> 
 
    </form>

+0

'errorMessage' non viene attivato se l'età è fornito meno di 18 –

Problemi correlati