2010-01-03 11 views
21

Ich habe einige Entwicklung mit dem xVal Framework für .NET, um einige der Validierungsregeln für Modelle auf der Serverseite zusammen mit einigen Client-Seite Validierung mit der jQuery Validation plugin zusammen mit der jQuery Form plugin für die Übermittlung des Formulars verknüpfen.Wie verwendet man das jQuery Validation Plugin mit Metadaten, jQuery Forms und xVal zusammen?

Allerdings habe ich Probleme, sie alle miteinander zu verbinden.

Ich versuche folgendes zu erreichen:

  1. der Client erlauben grundlegende Validierung definiert mithilfe von Regeln zur Durchführung von rules("add", options") Plugin für jQuery Validation Aufruf (das ist, was xVal verwendet Regeln auf der Serverseite definiert zu erhalten auf dem Modell).

  2. Wenn die Clientvalidierung erfolgreich ist, führen Sie den Aufruf an den Server aus, um die Formulardaten erneut einzugeben (bei Elementen, die auf dem Client validiert wurden, sowie bei jeder anderen Validierung, die im Client nicht durchgeführt werden konnte). .

  3. Lassen Sie den Server ein Objekt in JSON zurückgeben, das Fehler anzeigt, die möglicherweise bestimmte Felder enthalten, und dann die Fehleranzeige für die Felder festlegen.

Ich habe die Metadaten für das Plugin in der ASP.NET MVC Seite durch einen Aufruf xVal in der folgenden Art und Weise:

<%= Html.ClientSideValidation<Model>("model") %> 

Dies schlägt sich in den folgenden auf der Client-Seite :

<script type="text/javascript"> 
xVal.AttachValidator("model", 
{ 
    "Fields": 
    [ 
     { 
      "FieldName":"title", 
      "FieldRules": 
      [ 
       { 
        "RuleName":"Required", 
        "RuleParameters":{} 
       }, 
       { 
        "RuleName":"StringLength", 
        "RuleParameters": 
        { 
         "MaxLength":"250" 
        } 
       } 
      ] 
     }, 
     { 
      "FieldName":"body", 
      "FieldRules": 
      [ 
       { 
        "RuleName":"Required", 
        "RuleParameters":{} 
       } 
      ] 
     } 
    ] 
}, {}) 
</script> 

die oben wirklich übersetzt nur in eine Reihe von Anrufen an rules("add", options), die das jQuery-Validator-Plugin dann Prozesse.

Wenn Sie jedoch versuchen, dieses Formular über jQuery-Formulare zu senden, findet die Validierung nicht in den Formularwerten statt. Das Formular wird übermittelt, die Werte werden jedoch nicht validiert.

Wie kann ich das Formular mit dem jQuery Form-Plugin senden, während es durch das jQuery Validation-Plugin über einen Anruf an ajax validiert wird?

Antwort

5

Das wichtigste, was zu suchen, wenn alles zusammen setzen ist das kleine Stück Dokumentation (die für xVal nicht wirklich offensichtlich in der Dokumentation, die den Anruf zu rules("add", options) im Aufruf von xVal.AttachValidator abstrahiert) für rules("add", options) (Hervorhebung von mir):

Fügt die angegebenen Regeln und gibt alle Regeln für die erste abgestimmte Element. Erfordert, dass das übergeordnete Formular validiert ist, das heißt $ ("Formular"). Validate() wird zuerst genannt.

Dies ist besonders wichtig, wenn die jQuery-Formular-Plug-ins Spiel kommt, und Sie wollen das Formular über AJAX unterbreiten, wie Sie eine submitHandler Option in dem Aufruf von validate(options) einzurichten haben, etwa so:

<script type="text/javascript"> 
    $(document).ready(function() { 
     // Initialize the form. Store the validator. 
     var validator = $("form").validate({ 

      // Called when the form is valid. 
      submitHandler: function(form) { 

       // Submit the form via ajax. 
       $(form).ajaxSubmit({ 

        // The return data type is json. 
        dataType: "json", 

        // The callback on a successful form 
        // submission. 
        success: function(data, statusText) { 

         // If the new location is not null, then 
         // redirect to that location. 
         if (data.data.newLocation) { 
          // Go to the new location. 
          document.location.href = data.data.newLocation; 

          // Get out. 
          return; 
         } 

         // There are errors, pass them to the validator 
         // for display. 
         validator.showErrors(data.data.errors); 
        } 
       }); 
      } 
     }); 
    }); 
</script> 

Aufgrund der Dokumentation oben in Bezug auf Anrufe zu rules("add", options) zitiert, der Anruf an validate(options) muss vor den Anrufen zu rules("add", options).

Wenn nicht, dann wird der submitHandler ignoriert, nie aufgerufen.

Am Ende bedeutet dies, dass Ihre Client-Seite Code wie folgt aussehen muss, wenn sie alle zusammen setzen:

<script type="text/javascript" src="jquery-1.3.2.min.js"></script> 
<script type="text/javascript" src="jquery.validate.min.js"></script> 
<script type="text/javascript" src="jquery.form.js"></script> 
<!-- Note this is only needed if using xVal. --> 
<script type="text/javascript" src="xVal.jquery.validate.js"></script> 
<!-- The call to validate the form must come first. --> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     // Initialize the form. 
     $("form").validate({ 

      // Called when the form is valid. 
      submitHandler: function(form) { 

       // Submit the form via ajax. 
       $(form).ajaxSubmit({ 

        // The return data type is json. 
        dataType: "json", 

        // The callback. 
        success: function(data, statusText) { 

         // Alert the users to the message. 
         window.alert(statusText); 
        } 
       }); 
      } 
     }); 
    }); 
</script> 

<!-- Now make the calls to rules("add", options), AFTER the call to --> 
<!-- validate (options). It's separated into another block for  --> 
<!-- emphasis, but could be done in the block above.    --> 
<script type="text/javascript"> 
    // Make calls to rules("add", options). 
</script> 

<!-- Or, if you are using xVal, make the following call in the ASP.NET --> 
<!-- page but again, note it must come AFTER the call to    --> 
<!-- validate(options).            --> 
<%= Html.ClientSideValidation<Model>("model") %> 

schließlich mit all dies verdrahtet, ist das letzte, was zu tun, was zu tun, wenn die serverseitige Methode zurückgibt.

Sie möchten, dass der JSON, der von diesen Aufrufen zurückgegeben wird, eine standardisierte Viewmodel-Shell ist, in der Sie den antwortspezifischen Inhalt in ein standardisierteres Stück integrieren, das die benötigten Informationen über homogene Aufrufe verfügbar macht :

{ 
    // An integer, non-zero indicates faulure, with predefined ranges 
    // for standard errors across all operations, with other ranges for custom 
    // errors which are operation-specific. Examples of shared errors 
    // are not authenticated, not authorized, etc, etc. 
    resultCode: 0, 

    // A string, which is to be displayed to the user (usually in the 
    // form of a jQuery dialog, usually used for the common ranges of 
    // errors defined above. 
    message: null, 

    // An object with operation-specific results. 
    data: null 
} 

Für die Fehler auf dem Server, senden sie das gleiche wie oben, aber mit einer Stelle, die die URL hat, die der Benutzer auf Erfolg umgeleitet werden sollte (oder null, wenn es nicht erfolgreich war) und eine Karte das kann direkt an die showErrors(errors) Methode weitergegeben werden, wenn Fehler auf den Feldern sind:

{ 
    resultCode: 0, 

    message: null, 

    data: 
    { 
     // Returned as a string. If not null, then this is the url 
     // that the client should be redirected to, as the server-side 
     // operation was successful. 
     newLocation: null, 

     // If not-null, then this is a map which has the names of the 
     // fields with the errors, along with the errors for the fields. 
     errors: 
     { 
      "model.title": "The title already exists in the system.", 
      "model.body": "The body cannot have malicious HTML code in it." 
     } 
    } 
} 

Da die success field of the options parameter-ajaxSubmit geben sollte klar sein:

// The callback on a successful form 
// submission. 
success: function(data, statusText) { 

    // If the new location is not null, then 
    // redirect to that location. 
    if (data.data.newLocation) { 
     // Go to the new location. 
     document.location.href = data.data.newLocation; 

     // Get out. 
     return; 
    } 

    // There are errors, pass them to the validator 
    // for display. 
    validator.showErrors(data.data.errors); 
} 

Alles, was es ist zu sehen, tut überprüfen, ob die newLocation Eigenschaft definiert ist. Wenn es definiert ist, leitet es das aktuelle Dokument an den Speicherort um (normalerweise die URL der neu gespeicherten Ressource).

Wenn es nicht definiert ist, dann nimmt er die Karte und übergibt sie an showErrors am Münzprüfer durch einen Aufruf validate(options) zurückgegeben, die Fehlermeldungen Einstellen der Positionierung und Stil durch den Aufruf zu validate(options) angegeben ist.