簡體   English   中英

jQuery驗證:可變錯誤消息

[英]jQuery Validation: variable error messages

有用的參考資料:

問題:

  1. 為什么jQuery.validation“文檔”如此笨拙,甚至連基本示例都嚴重缺乏?

  2. 真正的問題:

我有一個做AJAX調用的自定義驗證器。 該調用可以返回各種值,這將需要不同的錯誤消息。 我似乎無法辨別如何根據響應來更改錯誤消息。 一些代碼:

<html>
<head>
<script>
// Set error value variable default & scope
var checkEmailErrorMessage = "API Error";

// AJAX Failure Error
checkEmailError = function(jqXHR, textStatus, errorThrown) {
    if (jqXHR.status == 404) {
        alert("Could not find the API Server (404)");
    } else {
        alert("Some horrifying error occurred: " + textStatus);
    }
    return false;
};

// AJAX Success Handler
checkEmailResponse = function(data, code, jqXHR) {
    switch (data.code) {
        case 200:
            return true;
        case 401:
            checkEmailErrorMessage = "Duplicate Email";
            alert("Sorry, our system has detected that an account with this email address already exists");
            break;
        case 403:
            checkEmailErrorMessage = "Invalid Email";
            alert("Sorry, our system has detected that this email is forbidden");
            break
        case undefined:
            alert("An undefined error occurred.");
            break;
        default:
            alert("A horrible error occurred.");
            break;
    }
    return false;
};

// The Custom Validator
jQuery.validator.addMethod("checkEmail", function(value, element) {

    $.ajax({
        type: "POST",
        cache: "false",
        async: "false",
        url: "/json/checkEmail",
        dataType: "json",
        data: {
            email: function() {
                return $("#email").val();
            }
        },
        success: checkEmailResponse,
        error: checkEmailError
    });

}, checkEmailErrorMessage);

// The Validator Settings
form_validation_settings = {
    onkeyup: false,
    rules: {
        "email": {
            required: true,
            minlength: 2,
            maxlength: 42,
            email: true,
            checkEmail: true
        }
    }
};

// The Binding
$(document).ready(function(){
    $('#MyForm').validate(form_validation_settings);
});

</script>
</head>

<body>

    <!-- the Form -->
    <form id="MyForm">
        <input type="text" name="email"/>
        <input type="submit" name="submit"/>
    </form>

</body>
</html>

無論如何,錯誤消息為“ API錯誤”。 驗證文檔狀態:

消息:可以是由“ jQuery.validator.format(value)”創建的函數。

但是我該如何裝配呢? 我要調用的任何函數都必須是AJAX調用的結果。

任何想法表示贊賞。 提前致謝!

您有兩種選擇:

  • 遠程通過要求您返回“ true”的JSON字符串來工作。 您可以通過AJAX調用將完整的錯誤消息作為帶引號的字符串返回:

偽代碼:

  print '"'.messages[code].'"';
  • 返回錯誤代碼,然后在ajax調用上使用dataFilter ,將其轉換為所需的消息:

在其他地方,您設置了一個message數組,如下所示:

 var messages = ['Code 0 error message','Code 1 error message', etc ];

       //in your validate rules
       remote: {
            url: 'foo.php',
            dataFilter: function (data, type) {
                return '"' + messages[data] + '"';
            },
            type: 'post'
        }    

選項1選項2的工作示例

只是遇到了同樣的問題,沒有看到一個對我想做的事情有用的答案,但是我能夠弄清楚該怎么做。 任何膽小的人現在請避開你的眼睛。

我想做的是提供有關拒絕該字段的確切原因的更詳細的信息,以便用戶不會猜測輸入的外觀。 驗證器需要檢查主機名和正則表達式非常復雜(順便說一句,您是否知道“ 0.256.1”是有效的主機名 ?!)

無論如何,這就是我能夠創建更詳細的錯誤消息的方式:

// helperfunctions.js
function validhostname(value) {
  if(value.length > 254) {
    return {pass: false, str: "hostname too long (" + value.length + ")." }
  }
  if(/[^a-zA-Z0-9\-_\.]/.test(value)) {
    return { pass: false, str: "No special characters besides '-' or '_'." }
  }
  ...
  return { pass: true,  str: "valid hostname." };
}

// clientfunctions.js
var hostnameval = {};

jQuery.validator.addMethod(
  "hostname", 
  function(value, element) {
    hostnameval = validhostname(value);
    return this.optional(element) || hostnameval.pass;
  },
  function() {
    var ret = hostnameval.str || "Invalid hostname.";
    hostnameval = {};
    return ret;
  }
);

到目前為止,在“方法”返回之前從未調用過“消息”,因此我還沒有看到“無效的主機名”。 顯示的字符串。 我希望這樣做的方法不那么笨拙,並且很高興能證明它的存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM