javascript 只允许小写字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8694023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:15:29  来源:igfitidea点击:

Allow only lowercase characters

javascriptjqueryregex

提问by Vpp Man

I use following code to check if a user input is lowercase or not. I will allow characters from ato z. no other characters allowed.

我使用以下代码来检查用户输入是否为小写。我将允许字符从az。不允许使用其他字符。

JavaScript file:

JavaScript 文件:

var pat = /[a-z]/;

function checkname()
{
  var t = $("input[name='user_name']").val();

  if(pat.test(t) == false)
  {
    alert('Only lowercase characters allowed');
  }
}
//... other functions

But this donot work all the time. If I enter industrialS, it will not find that capital 'S'.

但这并不总是有效。如果我输入industrialS,它不会找到大写的“S”。

I also tried: /^[a-z]$/and /[a-z]+/. But not working.

我也试过:/^[a-z]$//[a-z]+/。但不工作。

PLease help me.

请帮我。

回答by Pointy

Your regular expression just checks to see if the string has anylower-case characters. Try this:

您的正则表达式只是检查字符串是否有任何小写字符。试试这个:

var pat = /^[a-z]+$/;

That pattern will only match strings that have one or more lower-case alphabetic characters, and no other characters. The "^" at the beginning and the "$" at the end are anchors that match the beginning and end of the tested string.

该模式将仅匹配具有一个或多个小写字母字符的字符串,而不会匹配其他字符。开头的“^”和结尾的“$”是匹配测试字符串开头和结尾的锚点。

回答by Ananta Prasad

if((/[a-z]/.test(email))==true){//allow the small characters}

回答by 0lukasz0

Your regexp should be:

你的正则表达式应该是:

/^[a-z]+$/

回答by jacob

Since all you want is lower case letters, instead of just telling the user s/he's done something wrong, I would fix it:

由于您想要的只是小写字母,而不是仅仅告诉用户他/她做错了什么,我会修复它:

function checkname() {
    var disallowed = /[^a-z]/gi; // g=global , i=case-insensitive
    if (this.value == disallowed) {
        //delete disallowed characters
        this.value = this.value.replace(disallowed,'');
        alert('Only lowercase letters allowed');
        //instead of an alert, i would use a less intrusive fadeIn() message
    }
    this.value = this.value.toLowerCase();
}