Source code for schrodinger.ui.qt.appframework2.validators
import os
from schrodinger.ui.qt.appframework2.validation import ValidationResult
from schrodinger.ui.qt.appframework2.validation import ValidationResults
#=========================================================================
# Validator Base Classes
#=========================================================================
[docs]class Validator(object):
[docs] def __init__(self, target_obj):
if not hasattr(target_obj, 'validators'):
target_obj.__dict__['validators'] = []
if not hasattr(target_obj, '_validate'):
target_obj.__dict__['_validate'] = self.target_validate
target_obj.validators.append(self)
self.target_obj = target_obj
[docs] def target_validate(self, validate_children=False, stop_on_fail=True):
results = ValidationResults()
try:
validators = self.target_obj.validators
except AttributeError:
validators = []
for validator in validators:
if validator.validationEnabled():
results.add(validator._validate(stop_on_fail))
if not results and stop_on_fail:
return results
return results
[docs] def validationEnabled(self):
try:
return self.target_obj.isEnabled()
except AttributeError:
return True
def _validate(self, *args, **kwargs):
raise NotImplementedError('No _validate method implemented in %s' %
(self.__class__.__name__))
[docs]class BaseTextValidator(Validator):
[docs] def __init__(self, target_obj, text_getter=None, message=None):
Validator.__init__(self, target_obj)
if text_getter is None:
try:
text_getter = target_obj.text
except AttributeError:
pass
if text_getter is None:
try:
text_getter = target_obj.currentText
except AttributeError:
pass
if text_getter is None:
raise TypeError('Could not find text getter method')
self.getter = text_getter
if message is not None:
self.message = message
def _validate(self, *args, **kwargs):
text = self.getter()
return self.validateText(text)
[docs] def validateText(self, text):
raise NotImplementedError('No validateText method implemented in %s' %
(self.__class__.__name__))
#=========================================================================
# Actual Validators
#=========================================================================
[docs]class IsInteger(BaseTextValidator):
"""
A fairly useless validator, for demonstration purposes only.
"""
[docs] def validateText(self, text):
try:
int(text)
except ValueError:
return ValidationResult(False, '%s is not an integer' % text)
return True
[docs]class PathExists(BaseTextValidator):
[docs] def validateText(self, text):
if not os.path.exists(text):
return ValidationResult(False, 'Path not found')
return ValidationResult(True)
[docs]class FileExists(BaseTextValidator):
[docs] def validateText(self, text):
if not os.path.isfile(text):
return ValidationResult(False, 'File not found')
return ValidationResult(True)
[docs]class JobName(BaseTextValidator):
[docs] def validateText(self, text):
return True