我如何检查是否有一定数量的字符与JavaScript表单验证的答案

How do I check if there is a certain number of characters in an answer with JavaScript Form Validation

本文关键字:字符 JavaScript 答案 验证 表单 何检查 检查 是否      更新时间:2023-09-26

我有这个网站,你可以上传一些信息,它将被存储。我目前对它有一个验证,但我正试图使它更精确。我希望能够发送一个警报说…如果题目中有三个以上的点,答案。这是我得到的:

function ValidateContactForm()
{
    var name = document.ContactForm.sName;
    var ip = document.ContactForm.sIp;
    var port = document.ContactForm.sPort;
    var type = document.ContactForm.sType;
    var description = document.ContactForm.sDesc;
    if (name.value == "")
    {
        window.alert("Please enter a server name");
        name.focus();
        return false;
    }
    if (ip.value == "")
    {
        window.alert("Please enter an valid IP Address");
        ip.focus();
        return false;
    } else if (ip.value.length > 18) {
        window.alert("Please enter an valid IP Address");
        ip.focus();
        return false;
}
    if (port.value == "" || port > 4 || port < 6)
    {
        window.alert("Please enter a valid port number");
        port.focus();
        return false;
    }
    if (description.value == "")
    {
        window.alert("Please enter a description");
        description.focus();
        return false;
    }
    return true;
}

我想让它,如果有超过3个点在IP,它会提醒你。我该怎么做呢?由于

通过使用RegExp,我们可以匹配所有的点,并计算匹配次数。其他选项的JSPerf

if ((ip.value.match(/'./g) || []).length !== 3) {
    window.alert("Please enter a valid IP address");
    ip.focus();
    return false;
}

使用

number_of_dots = ((ip.value).split(".")).length - 1
if (number_of_dots > 3){
  alert("more than 3 dots")
}

获取IP地址中点的个数

Ip总是有4个点,所以你不需要纠结于3和4点Ip代码