I have String.

Var Str = "INC300051546,INC300051553,INC300051561,INC300051579"

I want to check there should not be seperator other than comma in the string.
And Comma Seperated String should contain INC as 1st three character and after that 9 digits followed by comma.

Is there any regular expression to validate the string.

Recommended Answers

All 2 Replies

Try this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test-String-Exg</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>

<title>Exam entry</title>
</head>

<body>
<script type="text/javascript">
$(function(){
    var str = "INC300051546,INC300051553,INC300051561,INC300051579";//Test your string here
    var seperators = ['.',';'];// add your expected seperators here
    var firstFlag = true;
    var secondFlag = true;
    var thirdFlag = true;
    var seperatorLength = seperators.length;

    //chacking other separator in the given string
    for(var i=0;i<seperatorLength;i++) {
        if(str.indexOf(seperators[i])>0) {
            firstFlag=false;
        }
    }

    if(firstFlag==true){
        var splitStr = str.split(',');
        for(var j=0;j<splitStr.length;j++){
            //check first 3 charectors equals to INC
            if(splitStr[j].substr(0, 3)!='INC')     secondFlag = false;
            // check other char number length is 9
            else if(splitStr[j].replace('INC','').length!=9) thirdFlag = false;
        }
        if(secondFlag == false) alert('INC is not in proper order');
        if(thirdFlag == false) alert('Error in 9 digits');
    }

    else alert('String contains other seperators');

});
</script>
</body>

There is a regex to check without going through those long checking above.

var str = "INC300051546,INC300051553,INC300051561,INC300051579"
if (str.match(/^INC\d{9}(,INC\d{9})*/)) { alert("OK") }
else { alert("NOT OK") }

If you want a case-insensitive, add i behind the last /.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.