validation_datetime.py 1.54 KB
from datetime import (
    datetime,
    date
)
from .base_validation import BaseValidation

class ValidationDateTime(BaseValidation):
    def __init__(self, cldr, params = {}):
        super(ValidationDateTime, self).__init__(cldr = cldr, params = params)
        
        self.__message          = self.rulemessage or 'Format :attribute bukan tidak benar. Format :format'

    def __get_datevalue(self):
        try:
            dt = datetime.strptime(str(self.value), str(self.rulevalue))
        except Exception as e:
            dt = None
        return dt

    def validate(self):
        ok  = True
        if isinstance(self.value, datetime) or isinstance(self.value, date):
            return ok

        if (self.value is None) or (self.value == ''):
            ok = not self.required
        else:
            dt = self.__get_datevalue()
            ok = (dt is not None)

        if not ok:
            self.colander_invalid[self.inputname] = self.__message.replace(':format', str(self.rulevalue).replace('%', '')).replace(':attribute', self.title)
            
        return ok


"""
eg:

def form_validator(form, value):
    cldr = colander.Invalid(form, 'Form input harus diisi')
    
    validations = {
        'tgl_lahir': {
            'rules': 'date:%d-%m-%Y',
            'messages': {
                'date'   : 'Format Tanggal Lahir salah. Gunakan format dd-mm-yyyy',
            }
        }
    }

    valid = FormValidator(
        cldr        = cldr,
        inputvalues = value,
        validations = validations
    )
    valid.validate()

"""