it-source

jQuery 검증자 및 AJAX를 사용하는 사용자 지정 규칙

criticalcode 2023. 2. 12. 17:58
반응형

jQuery 검증자 및 AJAX를 사용하는 사용자 지정 규칙

jQuery Validator에 대한 답변을 읽었습니다.이것에 의해, 데이타베이스내의 값에 대해서 유저명을 체크하는 방법을 개략적으로 설명합니다.

이 방법을 구현하려고 시도했지만 PHP 파일에서 어떤 내용이 반환되더라도 항상 사용자 이름이 이미 사용 중이라는 메시지가 나타납니다.

다음은 커스텀 메서드입니다...

$.validator.addMethod("uniqueUserName", function(value, element) {
  $.ajax({
      type: "POST",
       url: "php/get_save_status.php",
      data: "checkUsername="+value,
      dataType:"html",
   success: function(msg)
   {
      // if the user exists, it returns a string "true"
      if(msg == "true")
         return false;  // already exists
      return true;      // username is free to use
   }
 })}, "Username is Already Taken");

그리고 여기 인증 코드가 있습니다...

username: {
    required: true,
    uniqueUserName: true
},

php에서 메시지를 돌려주는 특별한 방법이 있나요?

감사해요.

A

그 밖에 이 문제에 부딪힌 사람은 2010년에는 없었던 「리모트」메서드를 서포트하고 있는지 확인합니다.

https://jqueryvalidation.org/remote-method/

$("#myform").validate({
  rules: {
    email: {
      required: true,
      email: true,
      remote: {
        url: "check-email.php",
        type: "post",
        data: {
          username: function() {
            return $("#username").val();
          }
        }
      }
    }
  }
});

AJAX 요청을 수행하고 있습니다.ergo: 커스텀 검증자가 true 또는 false를 반환할 때 검증은 이미 완료된 상태입니다.

다음 작업을 수행해야 합니다.async. 다음 게시물도 참조하십시오.jQuery가 비동기 Ajax 요청이 아닌 동기 Ajax 요청을 수행하도록 하려면 어떻게 해야 합니까?

예를 들어 다음과 같습니다.

function myValidator() {
   var isSuccess = false;

   $.ajax({ url: "", 
            data: {}, 
            async: false, 
            success: 
                function(msg) { isSuccess = msg === "true" ? true : false }
          });
    return isSuccess;
}

경고:

jQuery 1.8부터는 jqXHR($.Deferred)에서 async: false를 사용하는 것이 권장되지 않습니다.jqXHR.done()이나 폐지된jQXHR success() 등의 jqXHR 객체의 대응하는 메서드 대신 success/error/complete 콜백옵션을 사용해야 합니다.

페이지 내의 요소 값을 포함하는 jsonified 문자열을 원격 요청에 가져오는 방법을 찾는 데 오랜 시간이 걸렸습니다. 이는 여러 검색 결과를 조합하여 시도한 결과입니다.

요점:

  1. async:false더 이상 사용되지 않습니다.
  2. 직후의 함수 호출remote:는 요소의 값을 사용하여 데이터 문자열을 작성하기 위한 키입니다.다음 시간 이후 양식에서 현재 값에 액세스하려고 합니다.data:필드의 빈 값을 반환했습니다.dataTypejson으로 설정합니다.

        $("#EmailAddress").rules("add", {
        required: true,
        remote: function () { // the function allows the creation of the data string 
                              // outside of the remote call itself, which would not 
                              // return a current value from the form.
            var emailData = "{'address':'" + 
                            $('#SignupForm :input[id$="EmailAddress"]').val() + 
                            "'}";
            var r = {
                url: "foobar.aspx/IsEmailAvailable",
                type: "post",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                cache: false,
                data: emailData,
                dataFilter: function(response) {
                    this.email_run = true; //fix for race condition with next button
                    return isAvailable(data); //return true or false
                }
            };
            return r;
        },
        messages: {
            remote: "* Email in use"
        }
    });
    

.ASPX 페이지:

<input id="EmailAddress" required name="Email" type="email" placeholder="Email Address*" runat="server"/>

C# 코드 배후에 있음:

[WebMethod]
    public static object IsEmailAvailable(string address){...}

응답 개체 형식 지정:

function isAvailable(data) {
    var response = JSON.parse(getJsonObject(data));
    return (response.isAvailable === "True") ? true : false;
};

//transform response string to a JavaScript Object()
//http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/ 
function getJsonObject(data) {
    var msg = eval('(' + data + ')');
    if (msg.hasOwnProperty('d'))
        return msg.d;
    else
        return msg;
};

여기 내 "구식" 해킹이 있어

아래는 "jquery.validate.js" 라이브러리에서 "비동기" 검증을 사용할 수 있는 유틸리티 함수입니다.이 함수는 사용자 키 입력 사이에 지연을 발생시킵니다.그렇지 않으면 검증 함수 "validFunc"는 "모든 시간"으로 불리며, 이는 일부 상황에서는 그다지 수행되지 않으며 "서버사이드"/"백엔드"(기본적으로 ajax 호출)에서 검증을 수행하는 함수에 특히 문제가 됩니다.이와 같이 "validFunc" 유효성 검사 함수는 사용자가 특정 시간 동안 입력을 중지할 때만 호출되며, "실시간" 유효성 검사도 허용됩니다."onkeyup": truejqv 설정에서)를 입력합니다.

중요: "jqvAsyncValid" 함수를 사용하는 검증은 항상 비동기 때문에 다른 기능과의 경합을 피하기 위한 마지막 검증이어야 합니다.

{
    [...]
    "rules": {
        "field_name": {
            "required": true,
            "maxlength": 12,
            "minlength": 4,

            // NOTE: Validation involving the use of the "jqvAsyncValid" function. By Questor
            "my_custom_ajax_validation": true

        },
    [...]
}

답변 코드:

// NOTE: Adds the custom validation "my_custom_ajax_validation". By Questor
$.validator.addMethod("my_custom_ajax_validation", function (value, element) {
    return jqvAsyncValid(element, "my_custom_ajax_validation", myValidationFunc, this);
}, "My error message!");

// NOTE: My validation function. By Questor
function myValidationFunc(domElement) {
    if (someFuncWithAjaxCall(domElement.value) == "ALL_RIGHT!") {
        return true;
    } else {
        return false;
    }
}

// NOTE: Global "json" variable that stores the "status" ("isValid") and cycle control
// ("toCtrl") of asynchronously validated elements using the "jqvAsyncValid" function.
// By Questor
var jqvAsyncVState = {};

// NOTE: A utility function that allows the use of asynchronous validations with
// "jquery.validate.js". This function creates a delay between one user keystroke and
// another otherwise the validation function "validFunc" will be called "all time"
// which is not very performative in some circumstances and especially problematic
// for functions that perform validations on the serverside/backend (ajax calls basically).
// In this way the "validFunc" validation function is only called when the user stops
// typing for a certain period of time, which also allows a "realtime" validation
// as it occurs while the user is typing. By Questor
// [Ref .: https://jqueryvalidation.org/ ]
//. domElement - DOM element informed by jqv in the "addMethod" for the anonymous
// function;
//. asyncRuleNm - Validation name added via "addMethod";
//. validFunc - Function that will do the validation. Must have the signature
// "funcName(domElement)" returning "true" for valid and "false" for not;
//. jQValidInst - Instance of the current jqv within "addMethod". It is usually
// denoted by "this";
//. toInMsecs - "Timeout" in "milliseconds". If not informed the default will be
// 1500 milliseconds. Be careful not to use a very short timeout especially in
// "ajax" calls so as not to overload the serverside/backend.
// Eg.: `return jqvAsyncValid(element, "my_custom_ajax_validation", myValidationFunc, this);`.
function jqvAsyncValid(domElement, asyncRuleNm, validFunc, jQValidInst, toInMsecs) {
    if (typeof toInMsecs === "undefined" || toInMsecs === "") {
        toInMsecs = 1500;
    }
    var domEKey = jQValidInst.currentForm.id + domElement.name;

    // NOTE: The validation messages need to be "displayed" and "hidden" manually
    // as they are displayed asynchronously. By Questor
    function errMsgHandler() {
        if (jqvAsyncVState[domEKey]["isValid"]) {

            // NOTE: If the current error message displayed on the element was that
            // set in the rule added via "addMethod" then it should be removed since
            // the element is valid. By Questor
            // [Ref.: https://stackoverflow.com/a/11652922/3223785 ,
            // https://stackoverflow.com/a/11952571/3223785 ]
            if (jQValidInst.errorMap[domElement.name] == $.validator.messages[asyncRuleNm]) {
                var iMsgNow = {};
                iMsgNow[domElement.name] = "";
                jQValidInst.showErrors(iMsgNow);
            }

        } else {
            var iMsgNow = {};

            // NOTE: If the element is invalid, get the message set by "addMethod"
            // for current rule in "$.validator.messages" and show it. By Questor
            iMsgNow[domElement.name] = $.validator.messages[asyncRuleNm];
            jQValidInst.showErrors(iMsgNow);

        }
    }
    if (!jqvAsyncVState.hasOwnProperty(domEKey)) {

        // NOTE: Set the global json variable "jqvAsyncVState" the control attributes
        // for the element to be asynchronously validated if it has not already been
        // set. The key "domEKey" is formed by the "id" of the "form" that contains
        // the element and the element's "name". By Questor
        jqvAsyncVState[domEKey] = {
            "toCtrl": null,
            "isValid": undefined
        };

    }
    var useOnKeyup = true;

    // NOTE: The "onblur" event is required for "first validation" that only occurs
    // in a "blur" event - this is inherent to jqv - and for situations where the
    // user types very fast and triggers "tab" and the event "onkeyup" can not deal
    // with it. By Questor
    domElement.onblur = function (e) {
        jqvAsyncVState[domEKey]["isValid"] = validFunc(domElement);
        errMsgHandler();
        useOnKeyup = false;
    }
    if (useOnKeyup) {

        // NOTE: The strategy with the event "onkeyup" below was created to create
        // a "delay" between a "keystroke" and another one otherwise the validation
        // function "validFunc" will be called "all time" which is not very performative
        // in some circumstances and especially problematic for functions that perform
        // serverside/backend validations (ajax calls basically). In this way the
        // "validFunc" validation function is only called when the user stops typing
        // for a certain period of time ("toInMsecs"). By Questor
        domElement.onkeyup = function (e) {

            // NOTE: Clear the "toCtrl" if it has already been set. This will
            // prevent the previous task from executing if it has been less than
            // "toInMsecs". By Questor
            clearTimeout(jqvAsyncVState[domEKey]["toCtrl"]);

            // NOTE: Make a new "toCtrl" set to go off in "toInMsecs" ms. By Questor
            jqvAsyncVState[domEKey]["toCtrl"] = setTimeout(function () {
                jqvAsyncVState[domEKey]["isValid"] = validFunc(domElement);
                errMsgHandler();
            }, toInMsecs);
        };
    }
    return jqvAsyncVState[domEKey]["isValid"];
}

언급URL : https://stackoverflow.com/questions/2628413/jquery-validator-and-a-custom-rule-that-uses-ajax

반응형