2014-04-03 11 views
5

Chcę dodać kilka czeków dla moich formularzy, których stan jest związany z wartościami innych pól (tj. Mam formularz zakresu, a pole from musi być mniejsze niż to i viceversa). Nie znalazłem czegoś takiego na obecnych walidatorach, więc starałem się je dodać.Dodaj walidator Parsley.js z odniesionym polem

Więc dodałem te dwie funkcje Assert.prototype:

GreaterThanReference: function (reference) { 
    this.__class__ = 'GreaterThanReference'; 
    if ('undefined' === typeof reference) 
     throw new Error('GreaterThanReference must be instanciated with a value or a function'); 
    this.reference = reference; 
    this.validate = function (value) { 
     var reference = 'function' === typeof this.reference ? this.reference(value) : this.reference; 
     if ('' === value || isNaN(Number(value))) 
      throw new Violation(this, value, { value: Validator.errorCode.must_be_a_number }); 
     if (this.reference.value >= value) 
      throw new Violation(this, value); 
     return true; 
    }; 
    return this; 
} 

i

LessThanReference: function (reference) { 
    this.__class__ = 'LessThanReference'; 
    if ('undefined' === typeof reference) 
     throw new Error('LessThanReference must be instanciated with a value or a function'); 
    this.reference = reference; 
    this.validate = function (value) { 
     var reference = 'function' === typeof this.reference ? this.reference(value) : this.reference; 
     if ('' === value || isNaN(Number(value))) 
      throw new Violation(this, value, { value: Validator.errorCode.must_be_a_number }); 
     if (this.reference.value <= value) 
      throw new Violation(this, value); 
     return true; 
    }; 
    return this; 
} 

i te dwa pozostałe do ParsleyValidator.prototype.validators:

greaterthan: function (value) { 
    return $.extend(new Validator.Assert().GreaterThanReference(value), { 
     priority: 256, 
     requirementsTransformer: function() { 
     return { name : $(value).attr('alt'), value : +$(value).val() }; 
    }}); 
} 

i

lessthan: function (value) { 
    return $.extend(new Validator.Assert().LessThanReference(value), { 
     priority: 256, 
     requirementsTransformer: function() { 
     return { name : $(value).attr('alt'), value : +$(value).val() }; 
    }}); 
} 

Następnie chciałem dodać sprawdzane zaznaczenie w przywołanym polu, więc jeśli zmienię tylko wartość pola odnośnika, nadal mogę sprawdzić poprawność formularza (w przykładzie zakresu, jeśli zmienię wartość, powinienem zweryfikować pole. A jeśli zmienię na wartość, powinienem potwierdzić z pola). Aby to osiągnąć, ja edytowany ParsleyField.prototype.addConstraint:

addConstraint: function (name, requirements, priority, isDomConstraint, isReference) { 
    name = name.toLowerCase(); 
    if ('function' === typeof window.ParsleyValidator.validators[name]) { 
     var constraint = new ConstraintFactory(this, name, requirements, priority, isDomConstraint); 
     // if constraint is a referenced one, I add the specular constraint on the referenced field 
     if((name == 'lessthan' || name == 'greaterthan') && isReference !== true) { 
      // I check if I already instanciated the referenced ParsleyField 
      var referencedField = $(requirements).data('Parsley') && $(requirements).data('Parsley').__class__ == 'ParsleyField' ? 
       $(requirements).data('Parsley') : 
       new ParsleyField($(requirements), this.parsleyInstance).init(); 
      referencedField.addConstraint(name == 'lessthan' ? 'greaterthan' : 'lessthan', '#' + this.$element.attr('id'), priority, isDomConstraint, true); 
     } 
     // if constraint already exist, delete it and push new version 
     if ('undefined' !== this.constraintsByName[constraint.name]) 
      this.removeConstraint(constraint.name); 
     this.constraints.push(constraint); 
     this.constraintsByName[constraint.name] = constraint; 
    } 
    return this; 
} 

W szczegółach, dodałem isReference argument wiem czy już dodany odwrotnej ograniczenia w zakresie odsyłania, aby uniknąć odniesień okrężnych. Następnie, w dość okropny sposób, sprawdzam, czy ograniczenie, które dodaję, ma odniesienie i nie jest już ograniczeniem referencyjnym (może to być poprawione przez dodanie pewnego rodzaju "typu ograniczenia", który mógłby być pośredni (lub) dla więzów, które sprawdzają inne pola, i dla tych, którzy tylko sprawdzają wartość). Jeśli ten warunek jest prawdziwy, muszę dodać nowe ograniczenie do już zainicjowanego ParsleyField, lub jeśli nie zostało to zainicjowane, do nowego ParsleyField.

Ta metoda ma problem. Jeśli dodaję ograniczenie do pola, które odwołuje się do pola, które jeszcze nie zostało zainicjowane, kiedy normalny przepływ pietruszki dostaje się do tego pola, nadpisuje je, eliminując ograniczenie, które dodałem wcześniej.

Zero-pytanie: czy to właściwy sposób na osiągnięcie tego, czego chcę? Przyznaję, że nie zbadałem zbyt wiele Parsley API, ale chciałbym użyć mniej funkcji, jak to możliwe, ponieważ używam tej samej strony serwera kontroli i powinienem móc robić to samo po obu stronach.

Jeśli zero-odpowiedź to "tak", w jaki sposób mogę rozwiązać problem z nadpisywaniem? Prawdopodobnie powinienem być w stanie na instancję ParsleyField sprawdzić, czy już została zainicjowana, ale jak?

Odpowiedz

1

Nie wiem, której wersji pietruszki używasz, a może moja odpowiedź nie jest aktualna. Jednak napotkałem ten sam problem z wersją v.2.0.2. Na szczęście dokumenty zawierają samouczek do pisania niestandardowych weryfikatorów. Czy możesz sprawdzić następujące: https://github.com/mvpotter/parsley-extra-validators. Jeśli dobrze cię rozumiem, robią dokładnie to, czego potrzebujesz. Wszelkie opinie są mile widziane.

+0

Och, dziękuję!^_^W momencie, gdy pisałem pytanie, nie było żadnych dodatkowych walidatorów dla Parsley 2.0, sprawdzę je tak szybko, jak tylko będę mógł. – goffreder