Saurabh
Saurabh

Reputation: 19

I don't want to allow a 9 digit number in my textbox which is in format:123-12-1234 or 123456789

I am trying like this:

function k(){
  var x = $('#textArea').val();
  for (i = 0; i < x.length; i++)
  {
    if(x[i].match(/^[0-9]/))
    {
      if(x[i+1].match(/^[0-9]/) && x[i+2].match(/^[0-9]/) && x[i+3].match(/^[-]/) && x[i+4].match(/^[0-9]/) && x[i+5].match(/^[0-9]/) && x[i+6].match(/^[-]/) && x[i+7].match(/^[0-9]/) && x[i+8].match(/^[0-9]/) && x[i+9].match(/^[0-9]/) && x[i+10].match(/^[0-9]/))
      {
        if(x[i+11].match(/^[0-9]/))
        {
          return 'true';
        }
        else
        {
          return false;
        }
      }
      else if(x[i+1].match(/^[0-9]/) && x[i+2].match(/^[0-9]/) && x[i+3].match(/^[0-9]/) && x[i+4].match(/^[0-9]/) && x[i+5].match(/^[0-9]/) && x[i+6].match(/^[0-9]/) && x[i+7].match(/^[0-9]/) && x[i+8].match(/^[0-9]/))
      {
        if(x[i+9].match(/^[0-9]/))
        {
          return 'true';
        }
        else
        {
          return false;
        }
      }
      else
      {
        continue;
      }
    }
    else
    {
      continue;
    }
  }
  return 'true';
}

Upvotes: 1

Views: 94

Answers (3)

Krisztian Balla
Krisztian Balla

Reputation: 136

or using pure regexp

to match the 123-45-678 and 12345678 formats:

var x = $('#textArea').val();
if (x.match(/^\d{3}-\d{2}-\d{3}$|^\d{8}$/) {
  return true;
} else return false;

to match any number less then 9 digits:

var x = $('#textArea').val();
if (x.match(/^(?:\d-?){1,8}$/) {
  return true;
} else return false;

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68443

Or simply

var x = $('#textArea').val();
x = x.replace(/\D+/g,""); //first remove all non-digits from x
if (x.length <= 8 )
{
  return true;
}
return false;

Or if you only want to allow - and digits

var x = $('#textArea').val();
var matches = x.match( /[0-9-]/g ).length;
if ( !matches || matches.length != x.length ) 
{
  return false;
}
x = x.replace(/\D+/g,""); //first remove all non-digits from x
if (x.length <= 8 )
{
  return true;
}
return false;

Upvotes: 1

Rahul Patel
Rahul Patel

Reputation: 5244

function myFunc() {
   var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
   var x = document.getElementById("ssn");
   var res = patt.test(x.value);
   if(!res){
    x.value = x.value
        .match(/\d*/g).join('')
        .match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
        .replace(/-*$/g, '');
   }
}
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()">

Upvotes: 0

Related Questions