开发者

Javascript validation allowing spaces, hyphens, and foreign characters in names

开发者 https://www.devze.com 2023-03-24 11:45 出处:网络
I\'m currently using code like this: var alphaExp = /^[a-zA-Z]+$/; if (f_name.value.length &g开发者_JAVA技巧t; 1 && f_name.value.match(alphaExp)) {

I'm currently using code like this:

    var alphaExp = /^[a-zA-Z]+$/;
    if (f_name.value.length &g开发者_JAVA技巧t; 1 && f_name.value.match(alphaExp)) {
        // success
    }
    else {
        document.getElementById("f_name_mark").innerText = "<img src='images/icons/cross.png' class='mark'>";
        // fail
    }

However, alphaExp only accounts for upper- and lower-case English characters. How can I allow for foreign letters (é, å, ü etc) and spaces/hyphens?


You can try following regex:

/^[a-z- \xC0-\xFF]+$/i

Sample

JSFiddle

function validate() {
  var regex = /^[a-z- \xC0-\xFF]+$/i;
  var value = document.getElementById("txt").value;
  document.getElementById("result").innerHTML = regex.test(value) ? "valid": "incorrect"
}
<input type="text" id="txt">
<button onclick="validate()">Validate</button>
<p id="result"></p>

Encoding Reference


Insert \s to allow spaces. Add the others letters or symbols you want match.

var alphaexp = /^[a-zA-Z\séåü]+$/

0

精彩评论

暂无评论...
验证码 换一张
取 消