我正在使用 jQuery Mobile 最新版本和 jQuery。
我需要验证一个可以接受用户输入的字段。
如果输入不是数字,我希望在该字段附近有一个错误验证消息。
我想知道如何在 jQuery Mobile 中制作它。
另外我想知道是否可以强制用户只为字段添加数字值。
我正在使用 jQuery Mobile 最新版本和 jQuery。
我需要验证一个可以接受用户输入的字段。
如果输入不是数字,我希望在该字段附近有一个错误验证消息。
我想知道如何在 jQuery Mobile 中制作它。
另外我想知道是否可以强制用户只为字段添加数字值。
您可以使用http://docs.jquery.com/Plugins/Validation
如果您需要自定义验证,请查看addMethod( name, method, message )
此插件
您可以在 jquery mobile 中使用相同的jquery.validate.js
插件。formField
否则,您可以向所有需要验证的表单字段添加一个类,并在提交时获取包含字段的元素并进行自定义验证。如果您为每个页面使用哈希,我会写一些类似的东西:
<form class='myFormElem display-none'>
<div class="errorField"
<input type="text" data-regexp="^\+?[0-9]{10,15}$" class="formField">
<input type="submit" class="submitForm">
</form
示例代码片段:
$(location.hash + ' .submitForm').off('click');
$(location.hash + ' .submitForm').on('click', function (e) {
$(location.hash + ' .formField').each(function () {
var elem = $(this), p, regexp;
try {
//validate fields
p = elem.data('regexp');
if (p !== "" && p !== null && typeof p !== "undefined") {
regexp = new RegExp(p, ["g"]);
if (!val.match(regexp)) {
throw "Error..(your error message here)";
}
}
} catch (ex) {
$(errField).removeClass('display-none').addClass('display-block');
$(errField).html(ex);
}
}
});