我正在使用J查询Validate插件验证HTML表单,我想限制一些事情,以便用户不能输入零作为第一个数字。
例如:我有一个文本框可以输入任何项目的金额,因此用户不能输入零作为金额。
答案 0 :(得分:1)
您可以使用addMethod
由于您希望限制用户在文本字段中输入0作为第一个数字,因此可以使用正则表达式^[^0]\d*
来实现。
这是一个片段。
$.validator.addMethod("pattern", function(value, element, regexpr) {
return regexpr.test(value);
}, "Please enter a valid value.");
$("form").validate({
rules: {
cost: {
required: true,
//change regexp to suit your needs
pattern: /^[^0]\d*$/g
}
}
});
.form-group label.error {
color: maroon;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://jqueryvalidation.org/files/dist/jquery.validate.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<title>JS Bin</title>
</head>
<body>
<form class="form-inline">
<div class="form-group">
<label for="cost">Cost:</span>
<input class="form-control" id="cost" type="number" name="cost">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</body>
</html>