knockout.js 使用ko.observable进行电子邮件验证和电子邮件存在性检查

uinbv5nw  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(260)

我想应用验证的电子邮件,如果电子邮件是有效的或没有,并在数据库检查后使用 AJAX 来验证电子邮件已经存在,电子邮件已经exxt检查应该工作,如果第一次检查通过,这里是我做了什么,我在email_already_exist检查卡住,如何验证只有当上述检查通过,如果有人知道如何做

// code which checking email is valid
  email: ko.observable((ref = REGISTRY.unsavedUser) != null ? ref.email : void 0).extend({
    required: true,
    email: {
      params: true,
      message: 'Please enter a valid email.'
    },
    focus:true
  }),

  // function to check email exists
  var email_exist_check = function() {
  var errorElement = $('#parent-email-signup');
  var emzil = errorElement.val();

    return = $.ajax({
      url: '/api/v3/email_exists',
      method: 'POST',
      async: false,
      data: {
            email: emzil
          },
      success: function(data){

        console.log(data);

      },
      error: function (response, status) {
         showFlashMessage('An error occured, please try again later.', 'error');
      }
    });

};

电子邮件现有的功能是现成的iam卡住了,如何使用上面的代码,请帮助

iecba09b

iecba09b1#

永远不要永远不要在 AJAX 调用中使用async: false
您需要:
一个API Package 器,用于方便和以后的代码可读性。

const API = {
  email_exists: function (email) {
    return $.post('/api/v3/email_exists', {
      email: email
    }).then(function (result) {
      // evaluate result & return true (email exists) or false (email is free)
      return ...;
    }).fail(function (jqXhr, status, error) {
      showFlashMessage('An error occured, please try again later.', 'error');
      console.log('Error in email_exists', email, jqXhr, status, error);
    });
  },
  // add other API functions in the same way
};

async validation rule,它们调用您的API:

ko.validation.rules.emailFromAPI = {
  async: true,
  validator: function (val, params, callback) {
    API.email_exists(val).done(function (exists) {
      callback(!exists);    // validation is successful when the email does not exist
    });
  },
  message: 'Please enter a valid email.'
};

使用此规则的可观察对象:

email: ko.observable((ref = REGISTRY.unsavedUser) != null ? ref.email : void 0).extend({
  required: true,
  emailFromAPI: true,
  focus:true
}),
deikduxw

deikduxw2#

由于 AJAX 是异步的,你必须等待服务器响应,返回ajax调用不会等待服务器调用解析。解决这个问题的一种方法是使用回调(另一种方法是使用async/await进行承诺)

var email_exist_check = function(email, onSuccess, onError) {
  $.ajax({
    url: '/api/v3/email_exists',
    method: 'POST',
    async: false,
    data: { email },
    success: function(data){
      console.log(data);
      if (data && !data.error) { return onSuccess(); }
      return onError(data && data.error);
    },
    error: function (response, status) {
       onError(response);
    }
  });
};

// After doing a front-end email verification
email_exist_check(ref.email, () => {
    console.log('Email is valid');
}, (error) => {
    console.error('Something went wrong', error);
});

相关问题