簡體   English   中英

JavaScript中的文本框驗證

[英]Text box validation in javascript

如何驗證僅包含AZ和az字符,數字,空格,下划線和破折號的文本框? 文本框也不應接受西班牙語重音符號,如-á,-é,-í,-ó,-ú,-ü,-ñ,¿,¡。

使用正則表達式/[^a-z0-9\\s_-]/i檢查是否有除拉丁字母,數字,下划線或破折號以外的其他字符。

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

您應該使用如下正則表達式: /^[\\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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM