2013-04-24 81 views
0

我试图验证一个字符串,然后我用javascript发送信息到服务器。我想确保字符串长度是9,并且它只包含数字。regularexpression只验证数字字符串和长度

刚才提到,这个项目使用jquery移动控件。

这是我的HTML控件:

<div data-role="content" style="text-align: center;"> 
       <div data-role="fieldcontain"> 
        <label for="Childid"> 
         Child ID</label> 
        <input id="childid" class="textBox" value="" type="text"/> 

        <label for="ChildfirstName"> 
         Child first name</label> 
        <input id="ChildfirstName" class="textBox" value="" type="text"/> 

        <label for="Childlastname"> 
         Child last name</label> 
        <input id="ChildlastName" class="textBox" value="" type="text"/> 

       <label for="Childmail"> 
         Child Mail</label> 
        <input id="ChildMail" class="textBox" value="" type="text"/> 
       </div> 

       <label for="Childbudget"> 
         Child monthly budget</label> 
        <input id="childmbudget" class="textBox" value="" type="text"/> 

也是我写了这个功能:

function validateID(id) { 
    var re = /\d{9}/; 
    return re.test(id); 
} 

,并用它像这样:

var id = $('#childid').val(); 

if(validateID(id) == false) 
    $("#fillthefields").popup("open") 

但它似乎没有正确验证。

如果我已经问过,如何验证字符串只包含数字而不是以零数字开头?

回答

3

实际上您并不需要正则表达式。

你可以使用

return (id.length === 9 && !isNaN(id)); 

编辑:在回答塞缪尔的评论

MDN: isNaN()

MSDN: isNaN()

返回值

如果转换为Number类型的值为NaN,则为true,否则为false。

+0

你忘了'parseInt函数()''之前isNaN()' – 2013-04-24 10:15:58

+1

@SamuelLiew数转换为isNaN内部完成。编辑添加注释。 – 2013-04-24 10:18:08

+1

下来选民可以解释原因吗? – 2013-04-24 10:20:00

0

使用正则表达式,它会检查一个只包含9位数字的字符串,并且不以零开头。

var re = /^[1-9]\d{8}$/; 
0

变化

if(validateID(id) == false) 

if(validateID(id)) 

,改变你的正则表达式来

var re = /^[1-9]\d{8}$/; 
0

会HTML5模式工作?

pattern="[0-9]{9}" 

位不能与零

pattern="[1-9]{1}[0-9]{8}" title="Please enter 9 digits, can not start with 0" 

实施例开始:

参考

HTML

<h1>A Simple HTML5 Form Validation</h1> 
<p>Leave the field empty and submit the form to see what happens.</p> 

<form> 
    <label for="name">* Name</label> 
    <input type="text" id="name" pattern="[0-9]{9}" title="Please enter 9 digits" required> 
    <input type="submit" value="Submit"> 
</form> 

<footer>Which browsers support this feature? - <a href=http://caniuse.com/form-validation>Caniuse.com</a></footer>