How to generate alert if first 4 digits in a string are zero using Javascript

I have a form field that users can input a tag number that can only be 9 characters/digits long. The tag number can start with the following: FT followed by seven digits or characters, FM followed by seven characters/digits, or 000 plus 6 characters or digits. If the user inputs four zeros and then 5 digits/characters I need a JavaScript alert to tell them that the tag number cannot start with four zeros. I have tried regular expression by saying:

if (tagNumber ==(/^(0){4}[0-9a-zA-Z]$/)

That does not work because if the user inputs a tag number with 1,2 or,3 zeros then it sends the alert. I have also tried using jQuery slice() to pick at each number starting from the left but that does not work either. Anything else I can try.

Answers


You can use native .slice()

if("000056789".slice(0,4) === "0000"){
  alert("Cannot start with four zeroes");
}

Basically you can just do .slice(0,4) on your input string and validate if it is 0000


Try the following regex

/^0{4,}[1-9a-zA-Z]*$/mg

This matches invalid input

Demo: http://regex101.com/r/dH3gQ0


You can do it in different ways.

REGEX

 var re  = /^0{4}.*$/;
 // Incase if you want match only alpha numeric character, then 
 // var re  = /^0{4}[\w\d]*$/;

 re.test('0000434434')

indexOf

 var str = '0000434'
 // Check for indexOf '0000' is 0
 str.indexOf('0000') === 0

var result = "00004537".match(/^0{4}/);
if(result && result.length>0) {
   alert("number cannot start with four zeros");
}

if "result" not null(i.e. non empty array with the match), "0000" is found in the beginning of the string. else not found.


For strings .indexOf returns the position of the string you input. It will return -1 if not found, but will return 0 if the string is found at the start position, so this should work.

if ( tagNumber.indexOf( '0000' ) === 0 )
{
//
}

Need Your Help

monitoringDidFailForRegion when regioning for iBeacon, kCLErrorDomain error 5

ios monitoring core-location ibeacon ios7.1

I am working on a simple App that uses CoreLocation in iOS7.1 to determine a pre-set iBeacon.