Javascript的正则表达式返回true ..然后假..然后..真等 [英] Javascript regex returning true.. then false.. then true.. etc

查看:409
本文介绍了Javascript的正则表达式返回true ..然后假..然后..真等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题,我写一个窗体上的验证。这是一个检查用户名按钮旁边的输入。输入缺省值是用户名,例如Betamax录像机。当我preSS检查用户名它传递的正则表达式,并发送用户名到服务器。服务器的行为与预期,并返回2,告诉他们在提交自己的用户名的JavaScript。

然后,当我再次点击该按钮,正则表达式失败。没有被发送到服务器明显,因为该正则表达式已失败。假如我又回到preSS的按钮,正则表达式通行证,然后将用户名发送到服务器。

我简直想不出会是什么使得它做到这一点!这是没有意义的我!

编辑:我在Firefox和Chrome(MAC)测试的问题

这是我的code:

  $ J(下#用户名搜索),单击(checkUserName)。

功能checkUserName(){
    VAR的userName = $ J(下#用户名)VAL()。


    VAR invalidUserMsg =无效的用户名(A-ZA-Z0-9 _  - 不 - 或者_在开始或结束字符串);
    VAR过滤器= / ^ [^ -_]([A-Z0-9 -_] {4,20})[^ -_] $ / GI;
    如果(filter.test(用户名)){
        的console.log(通行证)
        $ j.post(
        /帐号/型材/ username_check /,
        {Q:用户名},
        功能(数据){
            如果(数据== 0){
                $ J(下#用户名搜索 - 结果)HTML(错误寻找的用户名再试一次?)。
            }
            否则,如果(数据== 5){
                $ J(下#用户名搜索 - 结果)HTML(invalidUserMsg)。
            }
            否则,如果(数据== 4){
                $ J(下#用户名搜索 - 结果)HTML(用户名太短或太长。)。
            }
            否则,如果(数据== 2){
                $ J(下#用户名搜索 - 结果)HTML(这已经是你的用户名。)。
            }
            否则,如果(数据== 3){
                $ J(下#用户名搜索 - 结果)HTML(这个用户名是采取)。
            }
            否则,如果(数据== 1){
                $ J(下#用户名搜索 - 结果)HTML(此用户名可用!)。
            }
        });
    } 其他 {
        的console.log(失败)
        $ J(下#用户名搜索 - 结果)HTML(invalidUserMsg)。
    }

    返回false;

}
 

中的HTML:

 <输入名称=用户名ID =用户名值={{user.username}}/>
<输入类型=按钮值=是不是有人吗? ID =用户名搜索>
<跨度ID =用户名搜索,结果>< / SPAN>
 

解决方案

  / ^ [^ -_]([A-Z0-9 -_] {4,20})[ ^ -_] $ / GI;
 

您正在使用先按g (全球)正则表达式。在JavaScript中,全球使用regexen有状态:你叫他们(与 EXEC 测试等)的第一次,你得到一个给定的字符串中的第一场比赛。再次打电话给他们,你会得到下一个匹配,依此类推,直到你斗不过并将其重置为下一个字符串的开始。你也可以写 regex.lastIndex = 0 重置这种状态。

(当然,这是一个非常糟糕的设计作品,保证混淆视听,引起奇怪的错误,欢迎JavaScript的!)

您可以省略先按g 正则表达式,因为你只测试了一场比赛。

另外,我不认为你想要 [^ -_] 在正面和背面。这将允许的任意的角色在每一端,IE浏览器。 *扑通!将是有效的。你可能会想先行/后向断言,但他们没有在JavaScript中使用。 (好吧,先行应该是,但它在IE浏览器坏了。)而不是建议:

  / ^ [A-Z0-9] [A-Z0-9 _-] {2,18} [A-Z0-9] $ / I
 

I have a strange problem with the validation I am writing on a form. It is a 'Check Username' button next to an input. The input default value is the username for example 'betamax'. When I press 'Check Username' it passes the regex and sends the username to the server. The server behaves as expected and returns '2' to tell the javascript that they are submitting their own username.

Then, when I click the button again, the regex fails. Nothing is sent to the server obviously because the regex has failed. If I press the button again, the regex passes and then the username is sent to the server.

I literally cannot figure out what would be making it do this! It makes no sense to me!

Edit: I've tested the problem in Firefox and Chrome (mac)

This is my code:

$j("#username-search").click(checkUserName);

function checkUserName() {
    var userName = $j("#username").val();


    var invalidUserMsg = 'Invalid username (a-zA-Z0-9 _ - and not - or _ at beginning or end of string)';
    var filter = /^[^-_]([a-z0-9-_]{4,20})[^-_]$/gi;
    if (filter.test(userName)) {
        console.log("Pass")
        $j.post(
        "/account/profile/username_check/", 
        { q: userName }, 
        function(data){
            if(data == 0) {
                $j("#username-search-results").html("Error searching for username. Try again?");
            }
            else if(data == 5) {
                $j("#username-search-results").html(invalidUserMsg);
            }
            else if(data == 4) {
                $j("#username-search-results").html("Username too short or too long.");
            }
            else if(data == 2) {
                $j("#username-search-results").html("This is already your username.");
            }
            else if(data == 3) {
                $j("#username-search-results").html("This username is taken.");
            }
            else if(data == 1){
                $j("#username-search-results").html("This username is available!");
            }
        });
    } else {
        console.log("fail")
        $j("#username-search-results").html(invalidUserMsg);
    }

    return false;

}

The HTML:

<input name="username" id="username" value="{{ user.username }}" />
<input type="button" value="Is it taken?" id="username-search">
<span id="username-search-results"></span>

解决方案

/^[^-_]([a-z0-9-_]{4,20})[^-_]$/gi;

You're using a g (global) RegExp. In JavaScript, global regexen have state: you call them (with exec, test etc.) the first time, you get the first match in a given string. Call them again and you get the next match, and so on until you get no match and it resets to the start of the next string. You can also write regex.lastIndex= 0 to reset this state.

(This is of course an absolutely terrible piece of design, guaranteed to confuse and cause weird errors. Welcome to JavaScript!)

You can omit the g from your RegExp, since you're only testing for one match.

Also, I don't think you want [^-_] at the front and back. That will allow any character at each end, ie. *plop! would be valid. You're probably thinking of lookahead/lookbehind assertions, but they're not available in JavaScript. (Well, lookahead is supposed to be, but it's broken in IE.) Suggest instead:

/^[a-z0-9][a-z0-9_-]{2,18}[a-z0-9]$/i

这篇关于Javascript的正则表达式返回true ..然后假..然后..真等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆