js中的空间验证

space validation in js?

本文关键字:验证 空间 js      更新时间:2023-09-26

我想限制网站名称上的空间使用(此处)。。

<tr>
    <td>
        <h4>Website Name</h4>
    </td>
    <td>
        <input type="text" name="wname" id="wname" size="30" required  onfocus="validateWebsite();" oninput="validateWebsite();">
        <select name="domain">
            <option selected>.com</option>
            <option>.in</option>
            <option>.net</option>
            <option>.org</option>
            <option>.edu</option>
            <option>.int</option>
        </select>
    </td>
</tr>

main.js文件包含以下代码
我想限制用户进入空间。有了可用的代码,它就不起作用了:

function validateWebsite()  {
    var s = document.getElementById('wname');
    if (s.indexOf(" ") !== -1){
        wname.setCustomvalidity('');
    }else{
        wname.setCustomValidity('Invalid Website');
    }
}

这:

if (s.indexOf(" ") !== -1)

应为:

if (s.value.indexOf(" ") === -1)

此外,第一个setCustomvalidity拼写错误(小写"v")。

试试这个。。。

    var s = document.getElementById('wname').value;
    if(s.trim().length == 0 || s.trim().indexOf(' ') != -1)
    {
         // Your code when string is just blank or having spaces
    }
    else
    {
         // Your code when string is not blank and not having any spaces
    }

希望它能帮助。。。