Coverage for portality/forms/validate.py: 77%
467 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 13:43 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 13:43 +0000
1import re
2from flask_login import current_user
3from wtforms import validators
4from wtforms.compat import string_types
5from typing import List
7from portality.core import app
8from portality.lib import dates
9from portality.lib.dates import FMT_DATE_STD
10from portality.models import Journal, EditorGroup, Account
12from datetime import datetime
13from portality import regex
14from portality.datasets import get_currency_code
15from portality.lib import isolang
18class MultiFieldValidator(object):
19 """ A validator that accesses the value of an additional field """
21 def __init__(self, other_field, *args, **kwargs):
22 self.other_field_name = other_field
23 super(MultiFieldValidator, self).__init__(*args, **kwargs)
25 @staticmethod
26 def get_other_field(field_name, form):
27 other_field = form._fields.get(field_name)
28 if not other_field:
29 if hasattr(form.meta, "parent_form"):
30 other_field = MultiFieldValidator.get_other_field(field_name, form.meta.parent_form)
31 else:
32 raise Exception('No field named "{0}" in form (or its parent containers)'.format(field_name))
33 return other_field
36class DataOptional(object):
37 """
38 Allows empty input and stops the validation chain from continuing.
40 If input is empty, also removes prior errors (such as processing errors)
41 from the field.
43 This is a near-clone of the WTForms standard Optional class, except that
44 it checks the .data parameter not the .raw_data parameter, which allows us
45 to check coerced fields correctly.
47 ~~DataOptional:FormValidator~~
49 :param strip_whitespace:
50 If True (the default) also stop the validation chain on input which
51 consists of only whitespace.
52 """
53 field_flags = ('optional', )
55 def __init__(self, strip_whitespace=True):
56 if strip_whitespace:
57 self.string_check = lambda s: s.strip()
58 else:
59 self.string_check = lambda s: s
61 def __call__(self, form, field):
62 if not field.data or isinstance(field.data, string_types) and not self.string_check(field.data):
63 field.errors[:] = []
64 raise validators.StopValidation()
67class OptionalIf(DataOptional, MultiFieldValidator):
68 # A validator which makes a field optional if another field is set
69 # and has a truthy value.
70 # ~~OptionalIf:FormValidator~~
72 def __init__(self, other_field_name, message=None, optvals=None, *args, **kwargs):
73 self.other_field_name = other_field_name
74 if not message:
75 message = "This field is required in the current circumstances"
76 self.message = message
77 self.optvals = optvals if optvals is not None else []
78 super(OptionalIf, self).__init__(*args, **kwargs)
80 def __call__(self, form, field):
81 other_field = self.get_other_field(self.other_field_name, form)
83 # if no values (for other_field) which make this field optional
84 # are specified...
85 if not self.optvals:
86 # ... just make this field optional if the other is truthy
87 if bool(other_field.data):
88 super(OptionalIf, self).__call__(form, field)
89 else:
90 # otherwise it is required
91 dr = validators.DataRequired(self.message)
92 dr(form, field)
93 else:
94 # if such values are specified, check for them
95 no_optval_matched = True
96 for v in self.optvals:
97 if isinstance(other_field.data, list):
98 if v in other_field.data and len(other_field.data) == 1:
99 # must be the only option submitted - OK for
100 # radios and for checkboxes where a single
101 # checkbox, but no more, is required to make the
102 # field optional
103 no_optval_matched = False
104 self.__make_optional(form, field)
105 break
106 if other_field.data == v:
107 no_optval_matched = False
108 self.__make_optional(form, field)
109 break
111 if no_optval_matched:
112 if not field.data:
113 raise validators.StopValidation('This field is required')
115 def __make_optional(self, form, field):
116 super(OptionalIf, self).__call__(form, field)
117 raise validators.StopValidation()
120class HTTPURL(validators.Regexp):
121 """
122 Simple regexp based url validation. Much like the email validator, you
123 probably want to validate the url later by other means if the url must
124 resolve.
126 ~~HTTPURL:FormValidator~~
128 :param require_tld:
129 If true, then the domain-name portion of the URL must contain a .tld
130 suffix. Set this to false if you want to allow domains like
131 `localhost`.
132 :param message:
133 Error message to raise in case of a validation error.
134 """
135 def __init__(self, message=None):
136 super(HTTPURL, self).__init__(regex.HTTP_URL, re.IGNORECASE, message)
138 def __call__(self, form, field, message=None):
139 message = self.message
140 if message is None:
141 message = field.gettext('Invalid URL.')
143 if field.data:
144 super(HTTPURL, self).__call__(form, field, message)
147class MaxLen(object):
148 """
149 Maximum length validator. Works on anything which supports len(thing).
151 Use {max_len} in your custom message to insert the maximum length you've
152 specified into the message.
154 ~~MaxLen:FormValidator~~
155 """
157 def __init__(self, max_len, message='Maximum {max_len}.', *args, **kwargs):
158 self.max_len = max_len
159 self.message = message
161 def __call__(self, form, field):
162 if len(field.data) > self.max_len:
163 raise validators.ValidationError(self.message.format(max_len=self.max_len))
166class RequiredIfRole(validators.DataRequired):
167 """
168 Makes a field required, if the user has the specified role
170 ~~RequiredIfRole:FormValidator~~
171 """
173 def __init__(self, role, *args, **kwargs):
174 self.role = role
175 super(RequiredIfRole, self).__init__(*args, **kwargs)
177 def __call__(self, form, field):
178 if current_user.has_role(self.role):
179 super(RequiredIfRole, self).__call__(form, field)
182class RegexpOnTagList(object):
183 """
184 Validates the field against a user provided regexp.
186 ~~RegexpOnTagList:FormValidator~~
188 :param regex:
189 The regular expression string to use. Can also be a compiled regular
190 expression pattern.
191 :param flags:
192 The regexp flags to use, for example re.IGNORECASE. Ignored if
193 `regex` is not a string.
194 :param message:
195 Error message to raise in case of a validation error.
196 """
197 def __init__(self, regex, flags=0, message=None):
198 if isinstance(regex, string_types):
199 regex = re.compile(regex, flags)
200 self.regex = regex
201 self.message = message
203 def __call__(self, form, field, message=None):
204 for entry in field.data:
205 match = self.regex.match(entry or '')
206 if not match:
207 if message is None:
208 if self.message is None:
209 message = field.gettext('Invalid input.')
210 else:
211 message = self.message
213 raise validators.ValidationError(message)
216class ThisOrThat(MultiFieldValidator):
217 """
218 ~~ThisOrThat:FormValidator~~
219 """
220 def __init__(self, other_field_name, message=None, *args, **kwargs):
221 self.message = message
222 super(ThisOrThat, self).__init__(other_field_name, *args, **kwargs)
224 def __call__(self, form, field):
225 other_field = self.get_other_field(self.other_field_name, form)
226 this = bool(field.data)
227 that = bool(other_field.data)
228 if not this and not that:
229 if not self.message:
230 self.message = "Either this field or " + other_field.label.text + " is required"
231 raise validators.ValidationError(self.message)
234class ReservedUsernames(object):
235 """
236 A username validator. When applied to fields containing usernames it prevents
237 their use if they are reserved.
239 ~~ReservedUsernames:FormValidator~~
240 """
241 def __init__(self, message='The "{reserved}" user is reserved. Please choose a different username.', *args, **kwargs):
242 self.message = message
244 def __call__(self, form, field):
245 return self.__validate(field.data)
247 def __validate(self, username):
248 if not isinstance(username, str):
249 raise validators.ValidationError('Invalid username (not a string) passed to ReservedUsernames validator.')
251 if username.lower() in [u.lower() for u in app.config.get('RESERVED_USERNAMES', [])]:
252 raise validators.ValidationError(self.message.format(reserved=username))
254 @classmethod
255 def validate(cls, username):
256 return cls().__validate(username)
259class OwnerExists(object):
260 """
261 A username validator. When applied to fields containing usernames it ensures that the username
262 exists
264 ~~OwnerExists:FormValidator~~
265 """
266 def __init__(self, message='The "{reserved}" user does not exist. Please choose an existing username, or create a new account first.', *args, **kwargs):
267 self.message = message
269 def __call__(self, form, field):
270 return self.__validate(field.data)
272 def __validate(self, username):
273 if not isinstance(username, str):
274 raise validators.ValidationError('Invalid username (not a string) passed to OwnerExists validator.')
276 if username == "":
277 return
279 acc = Account.pull(username)
280 if not acc:
281 raise validators.ValidationError(self.message.format(reserved=username))
283 @classmethod
284 def validate(cls, username):
285 return cls().__validate(username)
288class ISSNInPublicDOAJ(object):
289 """
290 ~~ISSNInPublicDOAJ:FormValidator~~
291 """
292 def __init__(self, message=None):
293 if not message:
294 message = "This ISSN already appears in the public DOAJ database"
295 self.message = message
297 def __call__(self, form, field):
298 if field.data is not None:
299 existing = Journal.find_by_issn(field.data, in_doaj=True, max=1)
300 if len(existing) > 0:
301 raise validators.ValidationError(self.message)
304class JournalURLInPublicDOAJ(object):
305 """
306 ~~JournalURLInPublicDOAJ:FormValidator~~
307 """
308 def __init__(self, message=None):
309 if not message:
310 message = "This Journal URL already appears in the public DOAJ database"
311 self.message = message
313 def __call__(self, form, field):
314 if field.data is not None:
315 existing = Journal.find_by_journal_url(field.data, in_doaj=True, max=1)
316 if len(existing) > 0:
317 raise validators.ValidationError(self.message)
320class StopWords(object):
321 """
322 ~~StopWords:FormValidator~~
323 """
324 def __init__(self, stopwords, message=None):
325 self.stopwords = stopwords
326 if not message:
327 message = "You may not enter '{stop_word}' in this field"
328 self.message = message
330 def __call__(self, form, field):
331 for v in field.data:
332 if v.strip() in self.stopwords:
333 raise validators.StopValidation(self.message.format(stop_word=v))
336class NotValue(object):
337 """
338 ~~NotValue:FormValidator~~
339 Rejects if the field value equals a forbidden string (case-insensitive).
340 """
341 def __init__(self, value, message=None):
342 self.forbidden = value
343 if not message:
344 message = "'{value}' is not a valid answer for this question. Leave blank.".format(value=value)
345 self.message = message
347 def __call__(self, form, field):
348 if self.forbidden is None:
349 return
350 if field.data and field.data.strip().lower() == self.forbidden.strip().lower():
351 raise validators.ValidationError(self.message)
354class ForbiddenWord(object):
355 """
356 ~~ForbiddenWord:FormValidator~~
357 Rejects if the field value contains a forbidden word (case-insensitive).
358 """
359 def __init__(self, word, message=None):
360 self.word = word
361 if not message:
362 message = "You may not enter '{word}' in this field".format(word=word)
363 self.message = message
365 def __call__(self, form, field):
366 if self.word is None:
367 return
368 if field.data and self.word.lower() in field.data.lower():
369 raise validators.ValidationError(self.message)
372class DifferentTo(MultiFieldValidator):
373 """
374 ~~DifferentTo:FormValidator~~
375 """
376 def __init__(self, other_field_name, ignore_empty=True, message=None):
377 super(DifferentTo, self).__init__(other_field_name)
378 self.ignore_empty = ignore_empty
379 if not message:
380 message = "This field must contain a different value to the field '{x}'".format(x=self.other_field_name)
381 self.message = message
383 def __call__(self, form, field):
384 other_field = self.get_other_field(self.other_field_name, form)
386 if other_field.data == field.data:
387 if self.ignore_empty and (not other_field.data or not field.data):
388 return
389 raise validators.ValidationError(self.message)
392class RequiredIfOtherValue(MultiFieldValidator):
393 """
394 Makes a field required, if the user has selected a specific value in another field
396 ~~RequiredIfOtherValue:FormValidator~~
397 """
399 def __init__(self, other_field_name, other_value, not_empty=False, message=None, *args, **kwargs):
400 self.other_value = other_value
401 self.not_empty = not_empty
402 self.message = message if message is not None else "This field is required when {x} is {y}".format(x=other_field_name, y=other_value)
403 super(RequiredIfOtherValue, self).__init__(other_field_name, *args, **kwargs)
405 def __call__(self, form, field):
406 # attempt to get the other field - if it doesn't exist, just take this as valid
407 try:
408 other_field = self.get_other_field(self.other_field_name, form)
409 except:
410 return
412 if self.not_empty:
413 if isinstance(other_field.data, list):
414 vals = [v for v in other_field.data if v]
415 if len(vals) > 0:
416 dr = validators.DataRequired(self.message)
417 dr(form, field)
418 else:
419 if other_field.data:
420 dr = validators.DataRequired(self.message)
421 dr(form, field)
422 return
424 if isinstance(self.other_value, list):
425 self._match_list(form, field, other_field)
426 else:
427 self._match_single(form, field, other_field)
429 def _match_single(self, form, field, other_field):
430 if isinstance(other_field.data, list):
431 match = self.other_value in other_field.data
432 else:
433 match = other_field.data == self.other_value
434 if match:
435 dr = validators.DataRequired(self.message)
436 dr(form, field)
437 else:
438 if not field.data or (isinstance(field.data, str) and not field.data.strip()):
439 raise validators.StopValidation()
441 def _match_list(self, form, field, other_field):
442 if isinstance(other_field.data, list):
443 match = len(list(set(self.other_value) & set(other_field.data))) > 0
444 else:
445 match = other_field.data in self.other_value
446 if match:
447 dr = validators.DataRequired(self.message)
448 dr(form, field)
449 else:
450 if not field.data or len(field.data) == 0:
451 raise validators.StopValidation()
453class StopValidationOnOtherValue(MultiFieldValidator):
454 def __init__(self, other_field_name, other_value, *args, **kwargs):
455 self.other_value = other_value
456 super(StopValidationOnOtherValue, self).__init__(other_field_name, *args, **kwargs)
458 def __call__(self, form, field):
459 # attempt to get the other field - if it doesn't exist, just take this as valid
460 try:
461 other_field = self.get_other_field(self.other_field_name, form)
462 except:
463 return
465 if isinstance(self.other_value, list):
466 self._match_list(form, field, other_field)
467 else:
468 self._match_single(form, field, other_field)
470 def _match_single(self, form, field, other_field):
471 if isinstance(other_field.data, list):
472 match = self.other_value in other_field.data
473 else:
474 match = other_field.data == self.other_value
475 if match:
476 raise validators.StopValidation()
477 else:
478 if not field.data or (isinstance(field.data, str) and not field.data.strip()):
479 raise validators.StopValidation()
481 def _match_list(self, form, field, other_field):
482 if isinstance(other_field.data, list):
483 match = len(list(set(self.other_value) & set(other_field.data))) > 0
484 else:
485 match = other_field.data in self.other_value
486 if match:
487 raise validators.StopValidation()
488 else:
489 if not field.data or len(field.data) == 0:
490 raise validators.StopValidation()
492class OnlyIf(MultiFieldValidator):
493 """
494 Field only validates if other fields have specific values (or are truthy)
495 ~~OnlyIf:FormValidator~~
496 """
497 def __init__(self, other_fields: List[dict], ignore_empty=True, message=None, *args, **kwargs):
498 self.other_fields = other_fields
499 self.ignore_empty = ignore_empty
500 if not message:
501 fieldnames = [n['field'] for n in self.other_fields]
502 message = "This field can only be selected with valid values in other fields: '{x}'".format(x=fieldnames)
503 self.message = message
504 super(OnlyIf, self).__init__(None, *args, **kwargs)
506 def __call__(self, form, field):
507 if field.data is None or field.data is False or isinstance(field.data, str) and not field.data.strip():
508 return
510 others = self.get_other_fields(form)
512 for o_f in self.other_fields:
513 other = others[o_f["field"]]
514 if self.ignore_empty and (not other.data or not field.data):
515 continue
516 if o_f.get("or") is not None:
517 # succeed if the value is in the list
518 if other.data in o_f["or"]:
519 continue
520 if o_f.get('not') is not None:
521 # Succeed if the value doesn't equal the one specified
522 if other.data != o_f['not']:
523 continue
524 if o_f.get('value') is not None:
525 if other.data == o_f['value']:
526 # Succeed if the other field has the specified value
527 continue
528 if o_f.get('value') is None:
529 # No target value supplied - succeed if the other field is truthy
530 if other.data:
531 continue
532 raise validators.ValidationError(self.message)
534 def get_other_fields(self, form):
535 # return the actual fields matching the names in self.other_fields
536 others = {f["field"]: self.get_other_field(f["field"], form) for f in self.other_fields}
537 return others
540class NotIf(OnlyIf):
541 """
542 Field only validates if other fields DO NOT have specific values (or are truthy)
543 ~~NotIf:FormValidator~~
544 """
546 def __call__(self, form, field):
547 others = self.get_other_fields(form)
549 for o_f in self.other_fields:
550 other = others[o_f["field"]]
551 if self.ignore_empty and (not other.data or not field.data):
552 continue
553 if o_f.get('value') is None:
554 # Fail if the other field is truthy
555 if other.data:
556 validators.ValidationError(self.message)
557 elif other.data == o_f['value']:
558 # Fail if the other field has the specified value
559 validators.ValidationError(self.message)
562class OnlyIfExists(OnlyIf):
563 """
564 Field only validates if other fields DOES have ANY values (or are truthy)
565 ~~NotIf:FormValidator~~
566 """
568 def __call__(self, form, field):
569 others = self.get_other_fields(form)
571 for o_f in self.other_fields:
572 other = others[o_f["field"]]
573 if not other.data or not field.data:
574 validators.ValidationError(self.message)
576class NoScriptTag(object):
577 """
578 Checks that a field does not contain a script html tag
579 ~~NoScriptTag:FormValidator~~
580 """
582 def __init__(self, message=None):
583 if not message:
584 message = "Value cannot contain script tag"
585 self.message = message
587 def __call__(self, form, field):
588 if field.data is not None and "<script>" in field.data:
589 raise validators.ValidationError(self.message)
592class GroupMember(MultiFieldValidator):
593 """
594 Validation passes when a field's value is a member of the specified group
595 ~~GroupMember:FormValidator~~
596 """
597 # Fixme: should / can this be generalised to any group vs specific to editor groups?
599 def __init__(self, group_field_name, *args, **kwargs):
600 super(GroupMember, self).__init__(group_field_name, *args, **kwargs)
602 def __call__(self, form, field):
603 group_field = self.get_other_field(self.other_field_name, form)
605 """ Validate the choice of editor, which could be out of sync with the group in exceptional circumstances """
606 # lifted from from formcontext
607 editor = field.data
608 if editor is not None and editor != "":
609 editor_group_name = group_field.data
610 if editor_group_name is not None and editor_group_name != "":
611 eg = EditorGroup.pull_by_key("name", editor_group_name)
612 if eg is not None:
613 if eg.is_member(editor):
614 return # success - an editor group was found and our editor was in it
615 raise validators.ValidationError("Editor '{0}' not found in editor group '{1}'".format(editor, editor_group_name))
616 else:
617 raise validators.ValidationError("An editor has been assigned without an editor group")
620class RequiredValue(object):
621 """
622 Checks that a field contains a required value
623 ~~RequiredValue:FormValidator~~
624 """
625 def __init__(self, value, message=None):
626 self.value = value
627 if not message:
628 message = "You must enter {value}"
629 self.message = message
631 def __call__(self, form, field):
632 if field.data != self.value:
633 raise validators.ValidationError(self.message.format(value=self.value))
636class BigEndDate(object):
637 """
638 ~~BigEndDate:FormValidator~~
639 """
640 def __init__(self, value, message=None):
641 self.value = value
642 self.message = message or "Date must be a big-end formatted date (e.g. 2020-11-23)"
644 def __call__(self, form, field):
645 if not field.data:
646 return
647 try:
648 datetime.strptime(field.data, FMT_DATE_STD)
649 except Exception:
650 raise validators.ValidationError(self.message)
653class DateInThePast(object):
654 def __init__(self, message=None):
655 self.message = message or "Date must be in the past"
657 def __call__(self, form, field):
658 if not field.data:
659 return
660 try:
661 d = datetime.strptime(field.data, FMT_DATE_STD)
662 except Exception:
663 raise validators.ValidationError(self.message)
665 if d > dates.now():
666 raise validators.ValidationError(self.message)
668class Year(object):
669 def __init__(self, value, message=None):
670 self.value = value
671 self.message = message or "Date must be a year in 4 digit format (eg. 1987)"
673 def __call__(self, form, field):
674 if not field.data:
675 return
676 return app.config.get('MINIMAL_OA_START_DATE', 1900) <= field.data <= dates.now().year
678class RequiredIfActive(object):
679 def __init__(self, message=None):
680 self.message = message or "This field is required if not disabled"
682 def __call__(self, form, field):
683 return
685class CustomRequired(object):
686 """
687 ~~CustomRequired:FormValidator~~
688 """
689 field_flags = ('required', )
691 def __init__(self, message=None):
692 self.message = message
694 def __call__(self, form, field):
695 if field.data is None or isinstance(field.data, str) and not field.data.strip() or isinstance(field.data, list) and len(field.data) == 0:
696 if self.message is None:
697 message = field.gettext('This field is required.')
698 else:
699 message = self.message
701 field.errors[:] = []
702 raise validators.StopValidation(message)
705class EmailAvailable(object):
706 """
707 ~~EmailAvailable:FormValidator~~
708 """
709 def __init__(self, message=None):
710 if not message:
711 message = "Email address is already in use"
712 self.message = message
714 def __call__(self, form, field):
715 if field.data is not None:
716 existing = Account.email_in_use(field.data)
717 if existing is True:
718 raise validators.ValidationError(self.message)
721class IdAvailable(object):
722 """
723 ~~IdAvailable:FormValidator~~
724 """
725 def __init__(self, message=None):
726 if not message:
727 message = "Account ID already in use"
728 self.message = message
730 def __call__(self, form, field):
731 if field.data is not None:
732 existing = Account.pull(field.data)
733 if existing is not None:
734 raise validators.ValidationError(self.message)
737class IgnoreUnchanged(object):
738 """
739 Disables validation when the input is unchanged and stops the validation chain from continuing.
741 If input is the same as before, also removes prior errors (such as processing errors)
742 from the field.
744 ~~IgnoreUnchanged:FormValidator~~
746 """
747 field_flags = ('optional', )
749 def __call__(self, form, field):
750 if field.data and field.object_data and field.data == field.object_data:
751 field.errors[:] = []
752 raise validators.StopValidation()
755class CurrentISOCurrency(object):
756 """
757 ~~EmailAvailable:FormValidator~~
758 """
759 def __init__(self, message=None):
760 if not message:
761 message = "Currency is not in the currently supported ISO list"
762 self.message = message
764 def __call__(self, form, field):
765 if field.data is not None and field.data != '':
766 value = field.data
767 if not isinstance(value, list):
768 value = [value]
769 for v in value:
770 check = get_currency_code(v, fail_if_not_found=True)
771 if check is None:
772 raise validators.ValidationError(self.message)
775class CurrentISOLanguage(object):
776 def __init__(self, message=None):
777 if not message:
778 message = "Language is not in the currently supported ISO list"
779 self.message = message
781 def __call__(self, form, field):
782 if field.data is not None and field.data != '':
783 value = field.data
784 if not isinstance(value, list):
785 value = [value]
786 for v in value:
787 check = isolang.find(v)
788 if check is None:
789 raise validators.ValidationError(self.message)