语义UI下拉用户添加仅允许电子邮件地址

时间:2017-02-24 23:17:34

标签: javascript jquery semantic-ui

该下拉菜单用于允许访问者搜索用户/电子邮件地址或输入自定义电子邮件地址。

我不希望他们能够添加用户添加,除非它是有效的电子邮件地址。一切都适用于远程API调用/搜索,并添加,但我有一个地狱的时间试图验证用户添加,甚至尝试使用一些jQuery黑客用户选择项目后,所有我悲惨地失败了。

听起来很简单吧?显然不适合我:(

基本上一切都有效,但如果它不是有效的电子邮件地址,则阻止他们添加用户添加。

这是一切jsFiddle: http://jsfiddle.net/tripflex/zewxp49s/

var excludeHasResults = false;

$.fn.dropdown.settings.templates.addition = function(search) {

  var output = 'Search results for';

  if (!excludeHasResults) {
    output = 'No users found for';
  }

  // Add search value to output
  output += ' <strong>' + search + '</strong>.  ';

  // Add to end of output based on valid email or not
  if (is_valid_email(search)) {
    output += ' <em>Click here to add ' + search + '</em>';
  } else {
    output += 'Please enter a valid email to add a custom email address';
  }

  return output;
};

$('#users_dd').dropdown({
  allowAdditions: true,
  apiSettings: {
    response: {
      success: true,
      results: [{
        'name': 'someone@somewhere.com',
        'value': 'someone@somewhere.com'
      }, {
        'name': 'someone2@somewhere2.com',
        'value': 'someone2@somewhere2.com'
      }, ]
    },
    onComplete: function(response) {
      // Check response for results, needed to format no results/add custom template value
      if (response && response.success && response.results) {
        if ($(response.results).length > 0) {
          // Set to TRUE so when "add" template function is called, it returns the right template
          excludeHasResults = true;
        } else {
          excludeHasResults = false;
        }
      }
    },
  },
  debug: true,
  hideAdditions: false,
  minCharacters: 3,
  showNoResults: true,
  message: {
    // $.fn.dropdown.settings.templates.addition handles template output
    addResult: '{term}',
  },
  onAdd: function(addedValue, addedText, $addedChoice) {
    console.log('onAdd', addedValue, addedText, $addedChoice);
    console.log($addedChoice);

    if (!is_valid_email(addedValue)) {
      console.log('invalid email, removing');
      $(this).dropdown('remove selected', addedValue);
    }
  },
  onLabelCreate: function(value, text) {
    console.log('onLabelCreate', value, text);
    console.log($(this));
    return $(this);
  },
  onLabelSelect: function($selectedLabels) {
    console.log('onLabelSelect', $selectedLabels);
  },
  onNoResults: function(searchValue) {
    console.log('onNoResults', searchValue);
    // Set variable false for no results/add custom template output
    excludeHasResults = false;
    return true;
  },
});

// Just basic email validation
function is_valid_email(email) {
  var re = /\S+@\S+\.\S+/;
  return re.test(email);
}

此示例允许任何用户添加,并且在花费数小时尝试使用不同方法后,我无法弄清楚如何对用户添加进行基本验证,并且只有在它是有效电子邮件时才允许。

除了我尝试过的其他很多东西之外,onAdd上的文档说“在使用多选下拉列表添加下拉选项后调用,只接收附加值”......但是它不会出现这种情况,如果您查看控制台,您会看到在onAdd ... wtf ??

之后调用onLabelCreate

原因是,我试图在onAdd回调中添加后删除下拉列表,但这显然不起作用,就像我尝试的其他所有内容一样......

啊哈哈,请有人帮我解决这个问题!

0 个答案:

没有答案