File: DateValidator.C

package info (click to toggle)
witty 3.1.2-3
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 45,512 kB
  • ctags: 35,832
  • sloc: cpp: 69,469; ansic: 66,945; xml: 4,383; sh: 594; perl: 108; makefile: 106
file content (50 lines) | stat: -rw-r--r-- 1,254 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include "DateValidator.h"

#include <Wt/WString>
#include <boost/regex.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>

using namespace boost::gregorian;

/*
 * Disclaimer: I am clueless how to use boost::gregorian in a sensible way.
 *
 * That, together with the fact that I wanted to test WRegExpValiator
 * is the reason why I use a regular expression to get the
 * day/month/year fields, and boost::gregorian to check that the date
 * is a valid date.
 */

DateValidator::DateValidator(const date& bottom, const date& top)
  : WRegExpValidator("(\\d{1,2})/(\\d{1,2})/(\\d{4})"),
    bottom_(bottom),
    top_(top)
{ 
  setNoMatchText("Must be a date in format 'dd/MM/yyyy'");
}

WValidator::State DateValidator::validate(WString& input) const
{
  WValidator::State state = WRegExpValidator::validate(input);

  std::string text = input.toUTF8();

  if ((state == Valid) && !text.empty()) {
    boost::smatch what;
    boost::regex_match(text, what, boost::regex(regExp().toUTF8()));

    try {
      date d
	= from_string(what[3] + "/" + what[2] + "/" + what[1]);

      if ((d >= bottom_) && (d <= top_))
	return Valid;
      else
	return Invalid;

    } catch (std::exception& e) {
      return Invalid;
    }
  } else
    return state;
}