3

I am having a problem to get the simple reges for alphanumeric chars only work in javascript :

var validateCustomArea = function () {
        cString = customArea.val();
        var patt=/[0-9a-zA-Z]/;
        if(patt.test(cString)){
            console.log("valid");
        }else{
            console.log("invalid");
        }
    }

I am checking the text field value after keyup events from jquery but the results are not expected, I only want alphanumeric charachters to be in the string

6
  • Shouldn't there be a semicolon on your third line there? Commented Oct 31, 2011 at 4:02
  • code is running fine it is just the results are wrong Commented Oct 31, 2011 at 4:05
  • @Dan: Semicolons are, in fact, optional in JavaScript. Commented Oct 31, 2011 at 4:05
  • I am guessing the regex above checks if in your string exists any, I want for my string to be only alphanumeric Commented Oct 31, 2011 at 4:05
  • 2
    @muistooshort Correct me if I'm wrong, but aren't they optional most of the time? Sometimes they are required, hence the good habit to always use them. Commented Oct 31, 2011 at 4:07

3 Answers 3

7

This regex:

/[0-9a-zA-Z]/

will match any string that contains at least one alphanumeric character. I think you're looking for this:

/^[0-9a-zA-Z]+$/
/^[0-9a-zA-Z]*$/ /* If you want to allow "empty" through */

Or possibly this:

var string = $.trim(customArea.val());
var patt   = /[^0-9a-z]/i;
if(patt.test(string))
    console.log('invalid');
else
    console.log('valid');
Sign up to request clarification or add additional context in comments.

Comments

2

Your function only checks one character (/[0-9a-zA-Z]/ means one character within any of the ranges 0-9, a-z, or A-Z), but reads in the whole input field text. You would need to either loop this or check all characters in the string by saying something like /^[0-9a-zA-Z]*$/. I suggest the latter.

Comments

2

I fixed it this way

var validateCustomArea = function () {
        cString = customArea.val();
        console.log(cString)
        var patt=/[^0-9a-zA-Z]/
        if(!cString.match(patt)){
            console.log("valid");
        }else{
            console.log("invalid");
        }
    }

I needed to negate the regex

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.