我在页面中添加了一些JavaScript验证,发现我找不到任何有用的资源来告诉我如何停止数值并允许它们放在不同的输入框中。我是JavaScript的新手,并没有完全掌握它。我知道VB有一个类似于我要求的命令:isNumeric()
以下是我想要停止数值的代码:
if (document.ExamEntry.name.value=="") {
alert("You must enter your name \n");
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
alert("You must enter the subject \n");
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
以下是我想要仅允许数值的代码:
if (document.ExamEntry.CadNumber.value.length!== 4) {
alert("Make sure you only have 4 numbers! \n");
document.ExamEntry.CadNumber.focus();
document.getElementById('CadNumber').style.color="red";
result = false;
}
--- --- EDIT
这是我到目前为止所得到的,但现在却有所不同......我想知道你是否知道了?
停止数值:
if (document.ExamEntry.subject.value) {
isNaN(parseInt(1));
alert("Please make sure you only have letters! \n");
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
仅允许数值:
if (document.ExamEntry.CadNumber.value) {
isNaN(parseInt(""));
alert("Please make sure you only have numbers! \n");
document.ExamEntry.CadNumber.focus();
document.getElementById('CadNumber').style.color="red";
result = false;
}
答案 0 :(得分:0)
查看isNaN
和parseInt
- 他们应该让您入门。来自JS控制台,
isNaN(parseInt("foo"))
true
isNaN(parseInt(12))
false
isNaN与您的VBA isNumeric相反,因此您需要在document.ExamEntry.CadNumber.value
上使用parseInt
像这样使用:
if (isNaN(parseInt(document.ExamEntry.CadNumber.value))) {
alert("Please make sure you only have numbers! \n");
document.ExamEntry.CadNumber.focus();
document.getElementById('CadNumber').style.color="red";
result = false;
}
答案 1 :(得分:0)
为了举例说明它是如何工作的,你可以查看这个小片段。
从某种意义上说,在您提交表单时,它将转到验证功能,然后检查您的表单是否符合要求。
仅限数字/文本隐含在类型中(您的浏览器也可以提供帮助),错误消息以标题形式提供。
当一个字段失败时,验证将停止并引发错误。
注意,如果你想要检查任何其他元素(比如选择),你还需要做一些额外的工作;)
如果您想了解有关您可以设置的元素类型的更多信息,您可以检查它here
function validate(form) {
var succeeded = true,
i, len, item, itemArray, firstErrorField;
if (!form) {
succeeded = false;
} else {
itemArray = form.getElementsByTagName('input');
for (i = 0, len = itemArray.length; i < len && succeeded; i++) {
item = itemArray[i];
switch (item.type) {
case 'text':
if ((!item.value && item.required) || !isNaN(parseInt(item.value))) {
succeeded = false;
}
break;
case 'number':
if ((!item.value && item.required) || isNaN(parseInt(item.value))) {
succeeded = false;
}
break;
}
if (!succeeded) {
firstErrorField = item.title || item.id || item.name;
}
}
}
if (!succeeded) {
alert('please check your input!\r\n' + firstErrorField);
}
return succeeded;
}
<form onsubmit="return validate(this);">
<fieldset>
<table>
<tr>
<td>Name:</td>
<td>
<input type="text" id="name" title="name is required" required />
</td>
</tr>
<tr>
<td>Age:</td>
<td>
<input type="number" id="age" required="required" min="0" title="age is required" />
</td>
</tr>
<tr>
<td colspan="2">
<button type="submit">Submit</button>
</td>
</tr>
</table>
</fieldset>
</form>