我在尝试使用javascript向服务器发送信息之前验证字符串。我想确保字符串长度为9,并且它只包含数字。
就是说,这个项目使用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")
但它似乎没有正确验证。
如果我已经问过,如何验证字符串只包含数字而不是以零数字开头?
答案 0 :(得分:3)
你实际上并不需要正则表达式。
你可以使用
return (id.length === 9 && !isNaN(id));
编辑:回复Samuel的评论
返回值
如果转换为Number类型的值是NaN,则为true,否则为false。
答案 1 :(得分:0)
使用正则表达式,它将检查一个只包含9位数的字符串,并且不会以零开头。
var re = /^[1-9]\d{8}$/;
答案 2 :(得分:0)
更改
if(validateID(id) == false )
到
if(validateID(id))
并将正则表达式更改为
var re = /^[1-9]\d{8}$/;
答案 3 :(得分: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>