2015-04-06 74 views

回答

3

代替正則表達式的,你可以比較的數值本身:

var ageValue = 50; // get the input age here 
var ageNumericVal = +ageValue; 
if (ageNumericVal < 0 || ageNumericVal > 200) { 
    // invalid 
} 
2

我強烈建議爲此使用if語句,因爲正則表達式在這種情況下效率不高。

無論如何,如果你真的想用正則表達式,請嘗試以下操作:

var age_regex=/\s[0-1]{1}[0-9]{0,2}/; 

Regex demo and explanation.

編輯:

使用的regex <input>

(工作演示)

p{ 
 
    color: red; 
 
}
<form action="#"> 
 
    Enter Age: <input type="text" name="number" pattern="[0-1]{1}[0-9]{0,2}" title="Please enter a valid number between 0 and 200."> 
 
    <input type="submit"> 
 
</form> 
 

 
<p>This form will give error if number does not pass the regex.</p>

 

+0

'\ S'將匹配任何非空格字符。 – 2015-04-06 07:24:40

+1

'\ s'匹配任何空格字符。 – 2015-04-06 07:27:08

+0

@AvinashRaj我相信OP有它的原因。 – 2015-04-06 07:28:05

1

你可以試試這個:

^(0?[1-9]|[1-9][0-9]|[1][1-9][1-9]|200)$ 

一個簡單的辦法來檢查年齡是不使用正則表達式和簡單的檢查是這樣的:

if(age >= 0 && age <= 200) 
{ 
    //code 
} 
+0

它可能是建築物的時代,或者... – nnnnnn 2015-04-06 07:32:10

+0

@nnnnnn: - 在觀看您的評論後已經刪除了該部分。謝謝! – 2015-04-06 07:33:37

+0

好的,收拾一下。 – 2015-04-06 07:36:48

0

你可以簡單地檢查if條件而不需要正則表達式,如:

if(input >=0 && input <= 200) { 
    //its valid 
}