html中的电话字段验证,允许数字和文本,但不允许@

时间:2019-01-15 21:03:17

标签: javascript html regex

此代码仅允许使用数字-优先选择允许输入破折号和/或方括号,例如ext等文本。但不是电子邮件地址。

您能帮我编辑此代码吗?非常感激。

  <input type="text" maxlength="40" onkeypress="return event.charCode >= 48 && event.charCode <= 57" required name="phone" id="phonecontactselection">

3 个答案:

答案 0 :(得分:0)

您需要一个仅检查@字符的函数来避免它,因此:

function avoidEmailPartCharacter(event) {
  const code = event.keyCode || event.which;
  if (code === 64) {
    event.preventDefault();
  }
}

然后将函数传递给输入keypress处理程序,如下所示:

<input type="type" keypress={avoidEmailPartCharacter(this)} />

应该可以解决问题

答案 1 :(得分:0)

最好将这种out模板逻辑转移到专用功能中,但是如果确实需要使其内联,则可以将输入字符与正则表达式进行匹配,如下所示:

$("<div class='dialog' title='" + title + "'><p>" + text + "</p></div>")
    .dialog({
        closeOnEscape: false,
        open: function (event, ui) {
            /* 
               What can I use to filter the two selectors below
               so that they only affect the current dialogs contents?
            */
            $(".ui-dialog-titlebar-close", ui.dialog | ui).hide();
            $('.ui-dialog-buttonpane', ui.dialog | ui).find('button').each(function (id, el) {
                /* This cycles through all buttons on all dialogs */
                debugger;
            });
        },
        buttons: {
            "Button 1": function () { doStuff; },
            "Button 2": function () { doStuff; },
            "Button 3": function () { doStuff; }
        }
    });

答案 2 :(得分:0)

您可以使用testcharacter class并列出允许匹配的字符。

在这种情况下,请匹配[],字符a-z,点或连字符之一:

[\][a-z.-]

<input 
 type="text" 
 maxlength="40" 
 onkeypress="return /[\][a-z.-]/.test(String.fromCharCode(event.which || event.keyCode));"   
 required 
 name="phone" 
 id="phonecontactselection"
>