使用 jquery validate 插件返回远程字符串

发布于 2024-09-04 02:24:47 字数 1206 浏览 2 评论 0原文

从jquery文档中,描述了jquery validate插件的远程功能:

响应被评估为 JSON,并且对于有效元素必须为 true,对于无效元素可以为任何 false、未定义或 null,使用默认消息;或字符串,例如。错误消息显示为“该名称已被占用,请尝试 peter123”。

I have a php page that echo's a response, and it works as described if I use echo("true") or echo("false"). However, whenever I echo a string, no error message is displayed, not even the default message. What must I do to echo back an error message and have it display in the error label next to the input box being validated?

这是我的 jquery 函数:

$(document).ready(function(){
    $("#masq").validate({ 
        rules: { 
             user: {
                required:true,
                minlength:1,
                remote:"<?=$_SERVER['PHP_SELF']?>?action=remoteCheck"
             }
        }, 
        messages: { 
            user: "id must have at least 1 character."
        } 
    });         
 });

和我的 php 函数:

//sql validation here
    if(!$user) {
        $return = "id " . $user . " does not exist."; 
        //echo("false"); works correctly
            echo($return); //does  
    }
    else {
        echo("true");
    }

From the jquery documentation, describing the remote function of the jquery validate plugin:


The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. "That name is already taken, try peter123 instead" to display as the error message.


I have a php page that echo's a response, and it works as described if I use echo("true") or echo("false"). However, whenever I echo a string, no error message is displayed, not even the default message. What must I do to echo back an error message and have it display in the error label next to the input box being validated?

here is my jquery function:

$(document).ready(function(){
    $("#masq").validate({ 
        rules: { 
             user: {
                required:true,
                minlength:1,
                remote:"<?=$_SERVER['PHP_SELF']?>?action=remoteCheck"
             }
        }, 
        messages: { 
            user: "id must have at least 1 character."
        } 
    });         
 });

and my php function:

//sql validation here
    if(!$user) {
        $return = "id " . $user . " does not exist."; 
        //echo("false"); works correctly
            echo($return); //does  
    }
    else {
        echo("true");
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

会傲 2024-09-11 02:24:47

我可以确认,如果您的服务器返回有效的 JSON(不仅仅是有效的 JS),则可以返回字符串。在 Ruby on Rails 中,我可以通过 "my string".to_json 来完成此操作,它会处理任何必要的转义。不确定 PHP 方法是什么。 JSON 字符串需要双引号,如下所示: 'My name is "Liam"'.to_json => ""我的名字是 \\"利亚姆 \\"""。无论您的服务器平台是什么,您都需要提供类似于 => 右侧的字符串。

I can confirm that if your server returns valid JSON (not just valid JS), returning a string is possible. In Ruby on Rails, I was able to accomplish this via "my string".to_json, which takes care of any escaping necessary. Not sure what the PHP approach would be. A JSON string needs to be doubly quoted, like this: 'My name is "Liam"'.to_json => ""My name is \\"Liam\\""". Whatever your server platform, you'll need to provide strings that look like what's on the right side of that =>.

醉酒的小男人 2024-09-11 02:24:47

我也遇到了这个问题(我需要向它传递多个值,并根据哪些条件返回 false,显示串联的错误消息,但这是另一篇 SO 发布的内容),但就像我最初所做的那样,您误解了文档的内容说 - 它只能返回 true 或 false (因为它以 JSON 格式传递) - 它所指的“字符串”是如果您使用 messages: code,然后指定与您的错误相关的消息:

这是一个示例(带注释):

$("#MemberInfo").validate({
    errorPlacement: function(error, element) {
           error.insertAfter(element);
       },
    rules: {    
        Memberemail: {
            required: true,
            email: true,
            remote: "checkReg.cfm"
        },

    },
    messages: {
        Memberemail: {
            required: "Please enter a valid email address",
            remote: jQuery.validator.format("{0} is already registered")    
        }
    }
});

服务器端代码返回“true”或“false”,消息中的 {0} 会将值从表单传递到服务器端脚本,并打印出该值以及自定义错误的其余部分该字段旁边显示的错误中的消息。

我仍在学习 JQuery,所以我希望这可以帮助您或其他任何人(如果这对您来说仍然是一个问题)!

I struggled with this too (I need to pass more than one value to it, and depending on which conditions return false, show concatenated error messages, but that's for another SO posting) , but like I did initially, you are misunderstanding what the documentation says - it can ONLY return true or false (because it's being passed in JSON format) - the "string" it is referring to is if you use the messages: code, and then specify a message related to your error:

Here's an example (with comments):

$("#MemberInfo").validate({
    errorPlacement: function(error, element) {
           error.insertAfter(element);
       },
    rules: {    
        Memberemail: {
            required: true,
            email: true,
            remote: "checkReg.cfm"
        },

    },
    messages: {
        Memberemail: {
            required: "Please enter a valid email address",
            remote: jQuery.validator.format("{0} is already registered")    
        }
    }
});

The server side code returns "true" or "false", and the {0} in the message puts the value passed to the server-side script from the form, and prints out that plus the rest of the custom error message in the error that appears next to the field.

I'm still learning JQuery, so I hope this helps you or anyone else out, if it's still an issue for you!

风吹雨成花 2024-09-11 02:24:47

正如文档所述,您需要输出有效的 JavaScript,因此请引用您的字符串(如果您的 ID 中可能包含引号或其他内容,请不要忘记转义):

$return = "\" id" . $user . " does not exist.\"";

您也不会输入

var foo = id 2 does not exist.;

JS,不是吗?

As the documentation states, you need to output valid JavaScript, so quote your string (and don't forget to escape if your ID might have quotes or whatnot in it):

$return = "\" id" . $user . " does not exist.\"";

You wouldn't type

var foo = id 2 does not exist.;

in JS either, would you?

罪#恶を代价 2024-09-11 02:24:47

我在 github 中输入了一个错误,但这应该可以回答您的问题。
这并不理想,但它会让你的东西发挥作用

场景
将表单上的日期与数据库中的日期进行比较。
使用远程调用PHP Lithium框架中的方法。
响应是一个 json 对象 {"data" : "true"} 或 {"data" : "please Enter a date Greater then xx/xx/xxxx"}

这会严重失败。
追踪它表明它在发帖时短路(我认为)。

如果我只传回一个字符串“true”或“false”,它就可以正常工作。
如果我传回“某种消息”而不是 false,它也会中断。

文档说我应该能够传回一条消息,好吧,如果我传递除布尔值以外的任何内容,它就会中断。
我不确定是否还需要添加标题或其他内容?

解决办法
我下载了实际的源文件(而不是使用cdn)
我将第 976 行和第 985 行从响应修改为 response.data 并使用了我原来的 json 对象。

I entered a bug into github, but this should answer your question.
Its not ideal, but it will get your stuff to work

Scenerio
Comparing a date on the form to a date in the database.
Used remote to call a method in PHP Lithium framework.
Response is a json object {"data" : "true"} or {"data" : "please enter a date greater then xx/xx/xxxx"}

This fails miserably.
Tracing it through shows it short circuits while doing the post ( I think).

If I pass back just a string "true" or "false" it works fine.
If I pass back "some kind of message" instead of false, it also breaks.

The documentation says I should be able to pass back a message, well, if I pass anything other then a boolean, it breaks.
I'm not sure if I also need to add a header or something?

Work around
I downloaded the actual source file (instead of using cdn)
I modified line 976 and 985 from response to response.data and used my original json object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文