javascript 验证单引号

标签 javascript

我的注册表中有一个密码字段。以下是javascript验证的代码。

if(document.getElementById('txtPassword').value == '' || document.getElementById('txtPassword').value == 'Password' ){
            alert("Please enter Password");
            document.getElementById('txtPassword').focus();
            return false;
        }


      else if (document.getElementById('txtPassword').value.length < 8)
       {
               alert('Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number');
               return false;
       }


      else if ( (! document.getElementById('txtPassword').value.match(/[a-z]/) ) || (! document.getElementById('txtPassword').value.match(/[A-Z]/) ) ) {
               alert('Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number');
               return false;
       }


      else if (!document.getElementById('txtPassword').value.match(/\d+/)) {
               alert('Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number');
               return false;
       }

        else if (document.getElementById('txtPassword').length < 8)
       {
               alert('Please ensure your password has at least eight characters, a mix of upper and lowercase and at least one number');
               return false;
       }

我需要检查单引号。如果用户在密码字段中输入单引号并按 Enter 键,则会弹出错误“避免在此字段中使用单引号”。

如何做到这一点?

最佳答案

else if (document.getElementById('txtPassword').value.indexOf("'") != -1) {
    alert("Avoid single quotes in this field");
    return false;
}

这是一个简单的测试用例。如果你制作一个 html 页面,将其放在 head 标签中,在浏览器中打开它,你会看到它的工作原理:

var value1 = "abc'def";
var value2 = "abcdef";
if(value1.indexOf("'") != -1)
    alert(value1 + " contains a '");
else
    alert(value1 + " does not contain a '");
if(value2.indexOf("'") != -1)
    alert(value2 + " contains a '");
else
    alert(value2 + " does not contain a '");

关于javascript 验证单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11807478/

相关文章:

javascript - D3和弦图

javascript - 如何使用ajax和php提交表单以避免页面刷新

javascript - 如何更改 cytoscape.js 中叠加层的形状和 z 索引?

javascript - 如何检测 GXT Combobox 中的实际值变化

javascript - 通过字长而不是字符数运行脚本

javascript - 将 Prop 发送到类外的 map 回调

javascript - 选项卡控件在 ASP.net MVC 中未按预期工作

javascript - 如何在 jQuery 中同时使用 OR 和 .find() ?

javascript - import() 相当于 import { some } from 'somewhere' ;

javascript - 遍历数组并分割值