skip to Main Content

I am validating strings in multiple formats.

  • Any integer x (matched) if(x < 2)no matched.
  • Numbers with hyphens x-y if(y > x) matched, x-y-z (no matched)
  • Format – x;y;z;g (matched), x;x;z;z (no matched)*

Always value >= 2

I created a regexp ^d+((;d+)*|-d+)?$ but there are problems:

  • 2 format if(y < x) matched
  • 3 format x;z;z matched

3

Answers


  1. You can split the string and process your parts individually:

    const valid = str => {
    
      const match = str.match(/^[d;]+$|^(d+)(-)(d+)$/);
      
      if(!match){
        return false;
      }
      
      const pos = 2; // position of '-' delimiter in the match
      if(match[pos] === '-'){
        return match[pos + 1] - match[pos - 1] > 0 && match[pos -1] >= 2;
      }
    
      const numbers = str.trim().split(/s*;s*/g);
      return numbers.every(num => num >=2) && new Set(numbers).size === numbers.length;
      
    }
      
    
    const strings = ["2;3;2", "5-4", "a;1", "2;301;44", "2", "2-3", "6-90", "2;3;4;5", "5;4", "2-3-5", "3;1"];
    
    for(const str of strings){
      console.log(str, ':', valid(str));
    }
    Login or Signup to reply.
  2. Using regex only, you can not do math.

    You can update your pattern using 3 capture groups, and then handle the x-y scenario using parseInt and make sure that y > x

    For the x;y;z scenario you can split on ; and check if there are no duplicate values.

    ^([2-9]|[1-9]d+)(?:-([2-9]|[1-9]d+)|((?:;d+)+))?$
    

    The pattern matches:

    • ^ Start of string
    • ([2-9]|[1-9]d+) Capture group 1, match either a digit 2-9 or 10+
    • (?: Non capture group for the 2 alternatives:
      • -([2-9]|[1-9]d+) Capture group 2, match - followed by a digit 2-9 or 10+
      • | Or
      • ( Capture group 3
        • (?:;d+)+ Match 1+ repetitions of ; and 1+ digits
      • ) Close group 3
    • )? Close the non capture group and make it optional
    • $ End of string

    Regex demo

    const regex = /^([2-9]|[1-9]d+)(?:-([2-9]|[1-9]d+)|((?:;d+)+))?$/;
    [
      "1", "1;1", "1-2", "3-2", "9-7", "9-8", "2", "2-1", "2-3", "5;4", "6-90", "3;2;1", "2;3;4;3", "6-90-1", "1;2;3", "2;3;4;1", "2;1;2", "2;3;4;9", "1;2;3;1", "2;301;44"
    ].forEach(s => {
      const m = s.match(regex);
      if (m) {
        const gr1 = parseInt(m[1]);
        if (undefined !== m[2] && parseInt(m[2]) > gr1)
          console.log(`Correct for ${s}`);
        if (undefined === m[2] && undefined === m[3])
          console.log(`Correct for ${s}`);
        if (undefined !== m[3]) {
          const parts = m[3].split(";").filter(Boolean).concat(m[1])
          if ((new Set(parts)).size === parts.length)
            console.log(`Correct for ${s}`);
        }
      }
    })
    Login or Signup to reply.
  3. To validate multiple formats using jQuery, you can utilize regular expressions (regex) to match the desired formats. Here’s an example of how you can implement this:

    <!DOCTYPE html>
    <html>
    <head>
      <title>Format Validation</title>
    </head>
    <body>
      <form id="form-example">
        <input type="text" id="myInput">
        <input type="submit" value="Submit">
      </form>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
      <script>
        $(document).ready(function() {
          $('#form-example').submit(function(event) {
            event.preventDefault(); // Prevent form submission
    
            // Get the input value
            var inputValue = $('#myInput').val();
    
            // Define the regex patterns for the allowed formats
            var emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,}$/;
            var phoneRegex = /^d{10}$/;
            var dateRegex = /^d{2}/d{2}/d{4}$/;
    
            // Check if the input matches any of the defined formats
            if (emailRegex.test(inputValue)) {
              alert('Valid email format');
            } else if (phoneRegex.test(inputValue)) {
              alert('Valid phone number format');
            } else if (dateRegex.test(inputValue)) {
              alert('Valid date format');
            } else {
              alert('Invalid format');
            }
          });
        });
      </script>
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search