2

I have one input field. It may contain either a name or a number.

If the input has at least one letter we handle it as name and its length should be 11 or lower. So valid input might be Bob, 12Bob or Bob23. No empty spaces or other chars are allowed so Bob_1, Bob 23 would be invalid.

If the input contains just digits we handle it as number, if so the number musts start with 00 and should be 16 in length or lower.

Here is my code:

function validateName(){
        var name = $('#absender').val();
        var length = name.length;
        if(/^[a-zA-Z0-9]+$/.test(name)){
            if(length > 11){
                $('#absender').addClass('error');
                $('#bsenderInfo').addClass('error');
                disableSave();
                return false;
            }else{
                $('#absender').removeClass('error');
                $('#absenderInfo').removeClass('error');
                enableSave();
                return true;
            }
        }else if(/^[0-9]+$/.test(name)){
            if(name.substring(0,2) != "00"){
                $('#absender').addClass('error');
                $('#bsenderInfo').addClass('error');
                disableSave();
                return false;
            }
            if(length > 17){
                $('#absender').addClass('error');
                $('#bsenderInfo').addClass('error');
                disableSave();
                return false;
            }else{
                $('#absender').removeClass('error');
                $('#absenderInfo').removeClass('error');
                enableSave();
                return true;
            }
        }else{
            $('#absender').addClass('error');
                $('#bsenderInfo').addClass('error');
                disableSave();
                return false;
        }   
      }

Does not matter what the input is, it gives me false if length is 12. Any ideas?

2 Answers 2

3

It's because of this line:

if(/^[a-zA-Z0-9]+$/.test(name)){

Every number string fits this regex well, so the "else" statement will be never executed.

You can correct this by checking the number-username case before checking the case [a-zA-Z0-9].

Sign up to request clarification or add additional context in comments.

1 Comment

Yea, swap the first and second conditional blocks around.
2

A single regex can handle it:

if (/^(00[0-9]{1,14}|[a-z0-9]{,11})$/i.test(name)) { 
    // Success condition
    ...
} else {
    // Failure condition
    ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.