检查数字是否按顺序排列 [英] check if numbers are in sequence
问题描述
我有一个文本框,其最大长度为4,如果用户按顺序输入数字,则需要抛出错误.
I have a textbox which contains a maxlength of 4 and if the user enters the numbers in sequence then needs to throw an error.
示例:以下是一些需要阻止的示例:
Examples: Below are few examples which needs to block:
1234、4567、5678等
1234, 4567, 5678 etc
它可以接受1233、4568等
And it can accept 1233, 4568 etc
我期望在Jquery或JavaScript中出现这种情况.
I'm expecting this condition in Jquery or JavaScript.
任何帮助将不胜感激
代码:我想使用以下格式的代码:
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.
推荐答案
最简单的解决方案是使用以下代码
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;
}, "");
只有在还需要反向序列验证的情况下,才需要使用变量numbersRev
的条件
The condition with the variable numbersRev
is only needed if the reverse sequence validation is also required
这篇关于检查数字是否按顺序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!