Projekt

Allgemein

Profil

« Zurück | Weiter » 

Revision ccfd9aac

Von Sven Schöling vor mehr als 6 Jahren hinzugefügt

  • ID ccfd9aace3d2c0a1199668e36d2deadbb871bd9b
  • Vorgänger 3791f895
  • Nachfolger 3efb443e

kivi.Validator

Unterschiede anzeigen:

js/kivi.Validator.js
1
namespace("kivi.Validator", function(ns) {
2
  "use strict";
3

  
4
  // Performs various validation steps on the descendants of
5
  // 'selector'. Elements that should be validated must have an
6
  // attribute named "data-validate" which is set to a space-separated
7
  // list of tests to perform. Additionally, the attribute
8
  // "data-title" must be set to a human-readable name of the field
9
  // that can be shown as part of an error message.
10
  //
11
  // Supported validation tests are:
12
  // - "required": the field must be set (its .val() must not be empty)
13
  //
14
  // The validation will abort and return "false" as soon as
15
  // validation routine fails.
16
  //
17
  // The function returns "true" if all validations succeed for all
18
  // elements.
19
  ns.validate_all = function(selector) {
20
    selector = selector || '#form';
21
    var to_check = $(selector + ' [data-validate]').toArray();
22

  
23
    for (var to_check_idx in to_check)
24
      if (!ns.validate($(to_check[to_check_idx])))
25
        return false;
26

  
27
    return true;
28
  };
29

  
30
  ns.validate = function($e) {
31
    var tests = $e.data('validate').split(/ +/);
32

  
33
    for (var test_idx in tests) {
34
      var test = tests[test_idx];
35

  
36
      if (ns.checks[test]) {
37
        if (!ns.checks[test]($e))
38
          return false;
39
      } else {
40
        var error = "kivi.validate_form: unknown test '" + test + "' for element ID '" + $e.prop('id') + "'";
41
        console.error(error);
42
        alert(error);
43
        return false;
44
      }
45
    }
46

  
47
    return true;
48
  }
49

  
50
  ns.checks = {
51
    required: function($e) {
52
      if ($e.val() === '') {
53
        ns.annotate($e, kivi.t8("This field must not be empty."));
54
        return false;
55
      } else {
56
        ns.annotate($e);
57
        return true;
58
      }
59
    },
60
    number: function($e) {
61
      var number_string = $e.val();
62

  
63
      var parsed_number = kivi.parse_amount(number_string);
64

  
65
      if (parsed_number === null) {
66
        $e.val('');
67
        ns.annotate($e);
68
        return true;
69
      } else
70
      if (parsed_number === undefined) {
71
        ns.annotate($e, kivi.t8('Wrong number format (#1)', [ kivi.myconfig.numberformat ]));
72
        return false;
73
      } else
74
      {
75
        var formatted_number = kivi.format_amount(parsed_number);
76
        if (formatted_number != number_string)
77
          $e.val(formatted_number);
78
        ns.annotate($e);
79
        return true;
80
      }
81
    },
82
    date: function($e) {
83
      var date_string = $e.val();
84

  
85
      var parsed_date = kivi.parse_date(date_string);
86

  
87
      if (parsed_number === null) {
88
        $e.val('');
89
        ns.annotate($e);
90
        return true;
91
      } else
92
      if (parsed_date === undefined) {
93
        ns.annotate($e, kivi.t8('Wrong date format (#1)', [ kivi.myconfig.dateformat ]));
94
        return false;
95
      } else
96
      {
97
        var formatted_date = kivi.format_date(parsed_date);
98
        if (formatted_date != date_string)
99
          $e.val(formatted_date);
100
        ns.annotate($e);
101
        return true;
102
      }
103
    }
104
  };
105

  
106
  ns.annotate = function($e, error) {
107
    if (error) {
108
      $e.addClass('kivi-validator-invalid');
109
      if ($e.hasClass('tooltipstered'))
110
        $e.tooltipster('destroy');
111

  
112
      $e.tooltipster({
113
        content: error,
114
        theme: 'tooltipster-light',
115
      });
116
      $e.tooltipster('show');
117
    } else {
118
      $e.removeClass('kivi-validator-invalid');
119
      if ($e.hasClass('tooltipstered'))
120
        $e.tooltipster('destroy');
121
    }
122
  };
123

  
124
  ns.reinit_widgets = function() {
125
    kivi.run_once_for('[data-validate]', 'data-validate', function(elt) {
126
      $(elt).change(function(event){ ns.validate($(elt), event) });
127
    });
128
  }
129

  
130
  ns.init = ns.reinit_widgets;
131

  
132
  $(ns.init);
133
});
js/kivi.js
31 31
  };
32 32

  
33 33
  ns.parse_date = function(date) {
34
    if (date === undefined)
35
      return undefined;
36

  
37
    if (date === '')
38
      return null;
39

  
34 40
    var parts = date.replace(/\s+/g, "").split(ns._date_format.sep);
35 41
    var today = new Date();
36 42

  
......
91 97
  };
92 98

  
93 99
  ns.parse_amount = function(amount) {
94
    if ((amount === undefined) || (amount === ''))
95
      return 0;
100
    if (amount === undefined)
101
      return undefined;
102

  
103
    if (amount === '')
104
      return null;
96 105

  
97 106
    if (ns._number_format.decimalSep == ',')
98 107
      amount = amount.replace(/\./g, "").replace(/,/g, ".");
......
101 110

  
102 111
    // Make sure no code wich is not a math expression ends up in eval().
103 112
    if (!amount.match(/^[0-9 ()\-+*/.]*$/))
104
      return 0;
113
      return undefined;
105 114

  
106 115
    amount = amount.replace(/^0+(\d+)/, '$1');
107 116

  
......
109 118
    try {
110 119
      return eval(amount);
111 120
    } catch (err) {
112
      return 0;
121
      return undefined;
113 122
    }
114 123
  };
115 124

  
......
283 292

  
284 293
    if (ns.Part) ns.Part.reinit_widgets();
285 294
    if (ns.CustomerVendor) ns.CustomerVendor.reinit_widgets();
295
    if (ns.Validator) ns.Validator.reinit_widgets();
286 296

  
287 297
    if (ns.ProjectPicker)
288 298
      ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
......
499 509
      console.log('No duplicate IDs found :)');
500 510
  };
501 511

  
512
  ns.validate_form = function(selector) {
513
    if (!kivi.Validator) {
514
      console.log('kivi.Validator is not loaded');
515
    } else {
516
      kivi.Validator.validate_all(selector);
517
    }
518
  };
519

  
502 520
  // Verifies that at least one checkbox matching the
503 521
  // "checkbox_selector" is actually checked. If not, an error message
504 522
  // is shown, and false is returned. Otherwise (at least one of them
......
514 532
    return false;
515 533
  };
516 534

  
517
  // Performs various validation steps on the descendants of
518
  // 'selector'. Elements that should be validated must have an
519
  // attribute named "data-validate" which is set to a space-separated
520
  // list of tests to perform. Additionally, the attribute
521
  // "data-title" must be set to a human-readable name of the field
522
  // that can be shown as part of an error message.
523
  //
524
  // Supported validation tests are:
525
  // - "required": the field must be set (its .val() must not be empty)
526
  //
527
  // The validation will abort and return "false" as soon as
528
  // validation routine fails.
529
  //
530
  // The function returns "true" if all validations succeed for all
531
  // elements.
532
  ns.validate_form = function(selector) {
533
    var validate_field = function(elt) {
534
      var $elt  = $(elt);
535
      var tests = $elt.data('validate').split(/ +/);
536
      var info  = {
537
        title: $elt.data('title'),
538
        value: $elt.val(),
539
      };
540

  
541
      for (var test_idx in tests) {
542
        var test = tests[test_idx];
543

  
544
        if (test === "required") {
545
          if ($elt.val() === '') {
546
            alert(kivi.t8("The field '#{title}' must be set.", info));
547
            return false;
548
          }
549

  
550
        } else {
551
          var error = "kivi.validate_form: unknown test '" + test + "' for element ID '" + $elt.prop('id') + "'";
552
          console.error(error);
553
          alert(error);
554

  
555
          return false;
556
        }
557
      }
558

  
559
      return true;
560
    };
561

  
562
    selector = selector || '#form';
563
    var ok   = true;
564
    var to_check = $(selector + ' [data-validate]').toArray();
565

  
566
    for (var to_check_idx in to_check)
567
      if (!validate_field(to_check[to_check_idx]))
568
        return false;
569

  
570
    return true;
571
  };
572

  
573 535
  ns.switch_areainput_to_textarea = function(id) {
574 536
    var $input = $('#' + id);
575 537
    if (!$input.length)
js/locale/de.js
56 56
"Edit text block":"Textblock bearbeiten",
57 57
"Enter longdescription":"Langtext eingeben",
58 58
"Error: Name missing":"Fehler: Name fehlt",
59
"Falsches Datumsformat!":"Falsches Datumsformat!",
60 59
"File upload":"Datei Upload",
61 60
"Function block actions":"Funktionsblockaktionen",
62 61
"Generate and print sales delivery orders":"Erzeuge und drucke Lieferscheine",
......
110 109
"The URL is missing.":"URL fehlt",
111 110
"The action can only be executed once.":"Die Aktion kann nur einmal ausgeführt werden.",
112 111
"The description is missing.":"Die Beschreibung fehlt.",
113
"The field '#{title}' must be set.":"Das Feld »#{title}« muss gesetzt sein.",
114 112
"The name is missing.":"Der Name fehlt.",
115 113
"The name must only consist of letters, numbers and underscores and start with a letter.":"Der Name darf nur aus Buchstaben (keine Umlaute), Ziffern und Unterstrichen bestehen und muss mit einem Buchstaben beginnen.",
116 114
"The option field is empty.":"Das Optionsfeld ist leer.",
......
123 121
"There are duplicate parts at positions":"Es gibt doppelte Artikel bei den Positionen",
124 122
"There are still transfers not matching the qty of the delivery order. Stock operations can not be changed later. Do you really want to proceed?":"Einige der Lagerbewegungen sind nicht vollständig und Lagerbewegungen können nachträglich nicht mehr verändert werden. Wollen Sie wirklich fortfahren?",
125 123
"There is one or more sections for which no part has been assigned yet; therefore creating the new record is not possible yet.":"Es gibt einen oder mehrere Abschnitte ohne Artikelzuweisung; daher kann der neue Beleg noch nicht erstellt werden.",
124
"This field must not be empty.":"Dieses Feld darf nicht leer sein.",
126 125
"This sales order has an active configuration for periodic invoices. If you save then all subsequently created invoices will contain those changes as well, but not those that have already been created. Do you want to continue?":"Dieser Auftrag besitzt eine aktive Konfiguration für wiederkehrende Rechnungen. Wenn Sie jetzt speichern, so werden alle zukünftig hieraus erzeugten Rechnungen die Änderungen enthalten, nicht aber die bereits erzeugten Rechnungen. Wollen Sie speichern?",
127 126
"Time/cost estimate actions":"Aktionen für Kosten-/Zeitabschätzung",
128 127
"Title":"Titel",
......
132 131
"Update quotation/order":"Auftrag/Angebot aktualisieren",
133 132
"Vendor missing!":"Lieferant fehlt!",
134 133
"Version actions":"Aktionen für Versionen",
134
"Wrong date format (#1)":"Falsches Datumsformat (#1)",
135
"Wrong number format (#1)":"Falsches Zahlenformat (#1)",
135 136
"Yes":"Ja",
136 137
"filename has not uploadable characters ":"Bitte Dateinamen ändern. Er hat für den Upload nicht verwendbare Sonderzeichen ",
137 138
"filesize too big: ":"Datei zu groß: ",
......
139 140
"sort items":"Positionen sortieren",
140 141
"start upload":"Hochladen beginnt",
141 142
"time and effort based position":"Aufwandsposition",
142
"uploaded":"Hochgeladen",
143
"wrongformat":"Falsches Format"
143
"uploaded":"Hochgeladen"
144 144
});
locale/de/all
1351 1351
  'Extended status'             => 'Erweiterter Status',
1352 1352
  'Extension Of Time'           => 'Dauerfristverlängerung',
1353 1353
  'Factor'                      => 'Faktor',
1354
  'Falsches Datumsformat!'      => 'Falsches Datumsformat!',
1355 1354
  'Fax'                         => 'Fax',
1356 1355
  'Features'                    => 'Features',
1357 1356
  'Feb'                         => 'Feb',
......
3158 3157
  'The export failed because of malformed transactions. Please fix those before exporting.' => 'Es sind fehlerhafte Buchungen im Exportzeitraum vorhanden. Bitte korrigieren Sie diese vor dem Export.',
3159 3158
  'The factor is missing in row %d.' => 'Der Faktor fehlt in Zeile %d.',
3160 3159
  'The factor is missing.'      => 'Der Faktor fehlt.',
3161
  'The field \'#{title}\' must be set.' => 'Das Feld »#{title}« muss gesetzt sein.',
3162 3160
  'The file has been sent to the printer.' => 'Die Datei wurde an den Drucker geschickt.',
3163 3161
  'The file is available for download.' => 'Die Datei ist zum Herunterladen verfügbar.',
3164 3162
  'The file name is missing'    => 'Der Dateiname fehlt',
......
3403 3401
  'This discount is only valid in sales documents' => 'Dieser Rabatt ist nur in Verkaufsdokumenten gültig',
3404 3402
  'This export will include all records in the given time range and all supplicant information from checked entities. You will receive a single zip file. Please extract this file onto the data medium requested by your auditor.' => 'Dieser Export umfasst alle Belege im gewählten Zeitrahmen und die dazugehörgen Informationen aus den gewählten Blöcken. Sie erhalten eine einzelne Zip-Datei. Bitte entpacken Sie diese auf das Medium das Ihr Steuerprüfer wünscht.',
3405 3403
  'This feature especially prevents mistakes by mixing up prior tax and sales tax.' => 'Dieses Feature vermeidet insbesondere Verwechslungen von Umsatz- und Vorsteuer.',
3404
  'This field must not be empty.' => 'Dieses Feld darf nicht leer sein.',
3406 3405
  'This function requires the presence of articles with a time-based unit such as "h" or "min".' => 'Für diese Funktion mussen Artikel mit einer Zeit-basierten Einheit wie "Std" oder "min" existieren.',
3407 3406
  'This general ledger transaction has not been posted yet.' => 'Die Dialogbuchung wurde noch nicht gebucht.',
3408 3407
  'This group is valid for the following clients' => 'Diese Gruppe ist für die folgenden Mandanten gültig',
......
3746 3745
  'Working copy; no description yet' => 'Arbeitskopie; noch keine Beschreibung',
3747 3746
  'Working on export'           => 'Generiere Export',
3748 3747
  'Write bin to default bin in part?' => 'Diesen Lagerplatz als Standardlagerplatz im Artikel setzen?',
3748
  'Wrong date format (#1)'      => 'Falsches Datumsformat (#1)',
3749 3749
  'Wrong field value \'#1\' for field \'#2\' for the transaction with amount \'#3\'' => 'Falscher Feldwert \'#1\' für Feld \'#2\' bei der Transaktion mit dem Umsatz von \'#3\'',
3750
  'Wrong number format (#1)'    => 'Falsches Zahlenformat (#1)',
3750 3751
  'Wrong tax keys recorded'     => 'Gespeicherte Steuerschlüssel sind falsch',
3751 3752
  'Wrong taxes recorded'        => 'Gespeicherte Steuern passen nicht zum Steuerschlüssel',
3752 3753
  'X'                           => 'X',
......
4090 4091
  'without skonto'              => 'ohne Skonto',
4091 4092
  'without_skonto'              => 'ohne Skonto',
4092 4093
  'working copy'                => 'Arbeitskopie',
4093
  'wrongformat'                 => 'Falsches Format',
4094 4094
  'yearly'                      => 'jährlich',
4095 4095
  'yes'                         => 'ja',
4096 4096
  'you can find professional help.' => 'finden Sie professionelle Hilfe.',

Auch abrufbar als: Unified diff