Programing

true .. 다음 false .. 다음 true .. 등을 반환하는 Javascript regex [duplicate]

lottogame 2020. 8. 28. 07:46
반응형

true .. 다음 false .. 다음 true .. 등을 반환하는 Javascript regex [duplicate]


양식에 작성중인 유효성 검사에 이상한 문제가 있습니다. 입력 옆에있는 '사용자 이름 확인'버튼입니다. 입력 기본값은 사용자 이름입니다 (예 : 'betamax'). '사용자 이름 확인'을 누르면 정규식을 전달하고 사용자 이름을 서버로 보냅니다. 서버는 예상대로 작동하고 '2'를 반환하여 자신의 사용자 이름을 제출하고 있음을 자바 스크립트에 알립니다.

그런 다음 버튼을 다시 클릭하면 정규식이 실패합니다. 정규식이 실패했기 때문에 분명히 서버에 아무것도 전송되지 않습니다. 버튼을 다시 누르면 정규식이 통과되고 사용자 이름이 서버로 전송됩니다.

나는 문자 그대로 이것이 무엇을 만드는지 알 수 없습니다! 나에게 말이 안돼!

편집 : Firefox 및 Chrome (mac)에서 문제를 테스트했습니다.

이것은 내 코드입니다.

$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;

}

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;

g(global)을 사용하고 RegExp있습니다. 자바 스크립트에서 글로벌 regexen 상태를 가지고 : 당신은 (그들을 호출 exec, test처음으로, 당신은 주어진 문자열에서 첫 경기를 얻을 수 등). 다시 전화하면 다음 일치 항목이 표시됩니다. 일치 항목이없고 다음 문자열의 시작 부분으로 재설정 될 때까지 계속됩니다. regex.lastIndex= 0이 상태를 재설정하기 위해 쓸 수도 있습니다 .

(물론 이것은 절대적으로 끔찍한 디자인으로, 혼란스럽고 이상한 오류를 일으킬 수 있습니다. JavaScript에 오신 것을 환영합니다!)

하나의 일치에 대해서만 테스트하므로 g에서 를 생략 할 수 있습니다 RegExp.

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

[a-z0-9-_]

This is wrong, The last - must be at the beginning or end.

[a-z0-9_-]

Whether that would cause this problem or not, I don't know.

Additional notes:

The first and last characters are allowed to be any character that isn't - or _ rather than being restricted to a-z0-9

a-z0-9 doesn't include uppercase characters. You need a-zA-Z0-9 for that. a-zA-Z0-9_ can be shortened to \w in most RegEx engines. I haven't tried it in JavaScript.

참고URL : https://stackoverflow.com/questions/2630418/javascript-regex-returning-true-then-false-then-true-etc

반응형