Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if numbers are in sequence

I have a textbox that contains a max length of 4 and if the user enters the numbers in sequence then needs to throw an error.

Examples: Below are a few examples which need to block:

1234, 4567, 5678, etc

And it can accept 1233, 4568, etc

I'm expecting this condition in Jquery or JavaScript.

Any help would be appreciated

Code: I want to use the code in below format:

$.validator.addMethod('Pin', function (b) {
    var a = true;    
    a = (/^([0-9] ?){4}$/i).test(b);    
    return a
}, '');

We can replace the condition which is in bold.


1 Answers

The simplest solution would be to use the following code

/**
* The sequential number would always be a subset to "0123456789".
* For instance, 1234, 4567, 2345, etc are all subset of "0123456789".
* To validate, this function uses 'indexOf' method present on String Object.
* you can read more about 'indexOf' at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
*/
$.validator.addMethod("Pin", function(b) {
  var numbers = "0123456789";
  //If reverse sequence is also needed to be checked
  var numbersRev = "9876543210";
  //Returns false, if the number is in sequence
  return numbers.indexOf(String(b)) === -1 && numbersRev.indexOf(String(b)) === -1;    
}, "");

The condition with the variable numbersRev is only needed if the reverse sequence validation is also required

like image 96
Sumit Surana Avatar answered Sep 13 '25 11:09

Sumit Surana