user240993
user240993

Reputation:

Javascript: Validation for special characters

I'm working on some validations and can't seem to wrap my head around checking for special chars, none should be used. Currently I grab the value, make an array and check for uppercase and numbers. I need a way to check for special chars as well. Another small issue I found is that it passes an uppercase when a number is entered. Just looking for some direction on how to tackle this.

$('.tooltip').on({  
    focusin: function(){ //make
        var top = $(this).offset().top 
        var left = $(this).offset().left + $(this).outerWidth()

        $('.tip').remove()
        $('body').append("<div class='tip' style='top:"+ top +"px;left:"+left+"px;'><div class='arrow'></div></div>")
        $('.tip').animate({width: 'show', opacity: 'show'})
        $(tipContent).appendTo('.tip')
    },
    focusout: function(){ //remove
        $('.tip').fadeOut(function(){$(this).remove()})
    },
    keyup: function(){ if (event.keyCode == 16) return //validate       
        var val = $(this).val()
        validate(val.split(""), val);
    },
})

function validate(letters, val){
    for (var i = 0; i < letters.length; i++){
        if( letters[i] === letters[i].toUpperCase() ) { //uppercase check
              console.log(letters[i] + ": " + 'Uppercase Passed');
        }else{console.log('Uppercase Failed');
        } 

        if( letters.length >= 9 ) { //min limit
              console.log(letters[i] + ": " + 'Minimum Limit Passed');
        }else{console.log('Minimum Limit Failed');
        }

        if( parseInt(letters[i]) > 0 ) { //number check
              console.log(parseInt(letters[i]) + ' passed');
        }else{console.log('at least 1 char failed');
        } 
    }
}

Upvotes: 1

Views: 178

Answers (1)

Bergi
Bergi

Reputation: 664513

An option might be to use regular expressions, which make your requirements easy to formulate:

function validate(value) {
    var regex = /^[A-Z0-9]*$/; // consist only of uppercase letters and digits
    var digit = /\d/; // contains a digit
    if (regex.test(value) && digit.test(value) && value.length >= 9)
        console.log("Test passed");
    else
        console.log("Test failed");
}

You even could combine them to one regex:

function validate(value) {
    return /^(?=.*\d)[A-Z0-9]{9,}$/.test(value);
//          |   |         |      |
//   string /   |     consists   \ string end
// beginning    |     of only
//              /     upper alphabet letters and numbers,
// somewhere ahead     at least 9 of them
// comes a digit
}

OK, if you need these steps separately, we should be able to do that. To recognice uppercase letters we just could use the regex [A-Z], but then umlauts etc wouldn't be recognized. If you handled them as special chars, we can easily use this regex:

/^(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]).{9,}$/
       |         |              |
     digit   uppercase    special char

If you don't want that (or the same regexes applied as single-steps), we can test for special characters with the following condition: It is not upper- or lower-caseable, and it is not a digit.

function validation(value) {
    var uc = false,
        lc = false,
        sc = false,
        di = false,
        len = value.length;
    for (var i=0; i<len; i++) {
        var letter = value.charAt(i),
            isUpper = letter.toUppercase() == letter,
            isLower = letter.toLowercase() == letter;
        if (isUpper && !isLower)
            uc = true;
        else if (isLower && !isUpper)
            uc = true;
        else // isLower && isUpper - no alphabetic character
            if (/\d/.test(letter))
                di = true;
            else
                sc = true;
    }
    return {
        someUppercase: uc,
        someLowercase: lc,
        someSpecial: sc,
        someDigit: di,
        length: len,
        longEnough: len >= 9
    };
}

Upvotes: 2

Related Questions