最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if numbers are in sequence - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question edited Oct 3, 2020 at 7:27 Penny Liu 17.4k5 gold badges86 silver badges108 bronze badges asked Sep 19, 2017 at 9:18 user3774781user3774781 2
  • I guess you can get some idea from stackoverflow./questions/9519640/… or stackoverflow./a/37811296/3855179 – Sumit Surana Commented Sep 19, 2017 at 9:21
  • 2 Can you not adapt your previous question, from only 2 hours ago? stackoverflow./questions/46293970/… – fdomn-m Commented Sep 19, 2017 at 9:27
Add a ment  | 

6 Answers 6

Reset to default 9

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/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

You can simply split the pin into individual digits, and iterate through them to ensure that there is at least one part that is not in sequential order (i.e difference of +2 or more):

$.validator.addMethod("Pin", function(value, element) {
  var digits = value.split(''),
      invalid = true;

  // Iterate through pairs of values
  // As long as one parison is not consecutive, the PIN is valid
  for(var i = 0; i < digits.length - 1; i++) {
    if (parseInt(digits[i]) - parseInt(digits[i+1]) > 1) {
      invalid = false;
      break;
    }
  }

  return !invalid;
}, "");

If you want to also acmodate for cases of descending sequences, i.e. 9876, simply check for the absolute difference between one digit to another, i.e.:

Math.abs(parseInt(digits[i]) - parseInt(digits[i+1])) > 1

Proof-of-concept logic:

// Test values
var values = ['1234', '1235', '4321', '5321'];

for(var v = 0; v < values.length; v++) {
  var value = values[v],
      digits = value.split(''),
      invalid = true;
      
  for(var i = 0; i < digits.length - 1; i++) {
    if (Math.abs(parseInt(digits[i]) - parseInt(digits[i+1])) > 1) {
      invalid = false;
      break;
    }
  }
  
  console.log('PIN: ' + value + '. Valid? ' + !invalid);
}

You can do like this:

//with array
var numArray = [1234, 1243];
for (var i = 0; i < numArray.length; i++) {
  checkIfSequential(numArray[i]);
}

//with string
var numberGiven = 1234;
checkIfSequential(numberGiven);


function checkIfSequential(num) {
  var newNum = num + ''
  newNum = newNum.split('');
  console.log(num + ': ' + newNum.every((num, i) => i === newNum.length - 1 || num < newNum[i + 1]));
}

I get your point, Why dont you just set the max length of the input field in the HTML itself and then bind a keyup event to the input box to trigger the validation ?

ex:

<input type="text" maxlength="4" onkeyup="validateMe()" id="key"/>

<script>
validateMe = function(){
 if(document.getElementById("key").value == "1234"){
    alert("yay! Key accepted!!");
 }
};
</script>

In order to fulfill the requirements for max length of 4 digits. We enumerate all possible sequential digits according to the OP constraints [1234, 2345, 3456, 4567, 5678, 6789], and then check them with the input arguments.

const sequentialDigits = (input) => {
  const allSeqNumsArr = [1234, 2345, 3456, 4567, 5678, 6789];
  return allSeqNumsArr.filter((num) => num === input).length > 0;
};

console.log(sequentialDigits(1234));
console.log(sequentialDigits(1235));
console.log(sequentialDigits(5321));

Here is actually the cleanest solution:

const sequential = (number) => '1234567890'.includes(String(number)) || '9876543210'.includes(String(number));

$.validator.addMethod('Pin', sequential, '');

With this, you can check the PIN in incremental and incremental order.

发布评论

评论列表(0)

  1. 暂无评论