Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does continuous validation of a string possible with regex

I'm trying to do a continuous validation on a string that contain a single special character also in the middle. Continuous validation means that even the partial string should return true.

By taking an example of a string like [four digits][a hyphen][three alphanumeric]

Cases
1) 1 Should validate
2) 432 Should validate
3) 1234- should validate
4) 1q21- Should not validate
5) 4532-a3s should validate
6) 8023-as12 should not validate

the regex i have now is

/^([0-9]{1,4})?\-([a-zA-Z0-9]{1,3})?$/;

This does not validate case 1 and 2 from the above listing

It does validate case 3, 4, 5, 6 from above cases

like image 301
Lalas M Avatar asked Dec 16 '25 20:12

Lalas M


2 Answers

You can try

^(\d{1,3}|\d{4}(-[a-z0-9]{0,3})?)$

Regex Demo (explanation included)

like image 125
vrintle Avatar answered Dec 19 '25 14:12

vrintle


I would use simple javascript to solve this problem. You loop through each character, check to see in which index range they fall in and apply validation there accordingly.

function validateString(str){
   if(str.length > 8 || str.length == 0) return false;
 	for(var i=0;i<str.length;++i){
     	if(i < 4){
         	if(!(str.charAt(i) >= '0' && str.charAt(i) <= '9')) return false;            
        }else if(i == 4){
        	if(str.charAt(i) != '-')  return false;           
        }else{
         	 if(!(str.charAt(i) >= '0' && str.charAt(i) <= '9' || str.charAt(i) >= 'a' && str.charAt(i) <= 'z' || str.charAt(i) >= 'A' && str.charAt(i) <= 'Z')) return false;
        }
    }  
      
    return true;
}
  const tests = [
	'1',
    '432',
    '1234-',
    '1q21-',
    '4532-a3s',
    '8023-as12',
    '1-2a',
    '1234ab',
    '1-a',
    '5555555555555',
    '5555qqq',
    '1234-@#@'
];
  
  
 tests.forEach((value) => {
     console.log(value + " => " + validateString(value));
 });
like image 36
nice_dev Avatar answered Dec 19 '25 15:12

nice_dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!