Projekt

Allgemein

Profil

« Zurück | Weiter » 

Revision fb63efe1

Von Moritz Bunkus vor mehr als 7 Jahren hinzugefügt

  • ID fb63efe1b63573c2ee3535cb2f9e63502dd0e848
  • Vorgänger 7ca30d76
  • Nachfolger 18709591

kivi.validate_form: generische Formvalidierung anhand von data-Attributen an Elementen

Unterschiede anzeigen:

js/kivi.js
474 474

  
475 475
    return false;
476 476
  };
477

  
478
  // Performs various validation steps on the descendants of
479
  // 'selector'. Elements that should be validated must have an
480
  // attribute named "data-validate" which is set to a space-separated
481
  // list of tests to perform. Additionally, the attribute
482
  // "data-title" must be set to a human-readable name of the field
483
  // that can be shown as part of an error message.
484
  //
485
  // Supported validation tests are:
486
  // - "required": the field must be set (its .val() must not be empty)
487
  //
488
  // The validation will abort and return "false" as soon as
489
  // validation routine fails.
490
  //
491
  // The function returns "true" if all validations succeed for all
492
  // elements.
493
  ns.validate_form = function(selector) {
494
    var validate_field = function(elt) {
495
      var $elt  = $(elt);
496
      var tests = $elt.data('validate').split(/ +/);
497
      var info  = {
498
        title: $elt.data('title'),
499
        value: $elt.val(),
500
      };
501

  
502
      for (var test_idx in tests) {
503
        var test = tests[test_idx];
504

  
505
        if (test === "required") {
506
          if ($elt.val() === '') {
507
            alert(kivi.t8("The field '#{title}' must be set.", info));
508
            return false;
509
          }
510

  
511
        } else {
512
          var error = "kivi.validate_form: unknown test '" + test + "' for element ID '" + $elt.prop('id') + "'";
513
          console.error(error);
514
          alert(error);
515

  
516
          return false;
517
        }
518
      }
519

  
520
      return true;
521
    };
522

  
523
    selector = selector || '#form';
524
    var ok   = true;
525
    var to_check = $(selector + ' [data-validate]').toArray();
526

  
527
    for (var to_check_idx in to_check)
528
      if (!validate_field(to_check[to_check_idx]))
529
        return false;
530

  
531
    return true;
532
  };
477 533
});
478 534

  
479 535
kivi = namespace('kivi');

Auch abrufbar als: Unified diff