javascript中的文本框验证

时间:2017-02-08 12:29:09

标签: javascript

如何验证文本框,该文本框仅允许字符A-Z& a-z,数字,空格,下划线和短划线字符?文本框也不应接受西班牙语口音和字母,如-á,-é,-í,-ó,-ú,-ü,-ñ,¿,¡,

2 个答案:

答案 0 :(得分:0)

使用正则表达式/[^a-z0-9\s_-]/i检查是否有除拉丁字母,数字,空格下划线或短划线之外的其他字符。

myString.test(/[^a-z0-9\s_-]/i);

答案 1 :(得分:0)

您应该使用这样的正则表达式:/^[\w-\s]+$/来测试输入是否正确。

^: from the begining
[\w-\s]: a combination of:
    \w: letters (latin), numbers and underscore
    - : dash
    \s: space
+: at least one time (at least one character long)
$: untill the end

示例:



var span = document.getElementById("span");

document.getElementById("input").oninput = function() {
  if(/^[\w-\s]+$/.test(this.value))
    span.classList.add("hidden");
  else
    span.classList.remove("hidden");
}

#span{
  color: red;
}

.hidden{
  display: none;
}

<input id="input"><span id="span">INVALID<span>
&#13;
&#13;
&#13;