1

我正在进行表单验证,要求是 1.Email:电子邮件必须是有效的电子邮件 ID。2.密码:必须是八个字符长。只允许使用数字 (0-9) 和字母 (AZ,az)。3.FirstName:不能包含任何数字(0-9)。4.LastName :不能包含任何数字(0-9)。我为电子邮件地址做了,我对密码和名字验证感到震惊.. 任何人都可以帮助我提前致谢。

    <form>
            <label for="">First Name</label>
            <input type="text" id="fname"><br>
            <label for="">Last Name</label>
            <input type="text" id="lname"><br>
            <label for="">Email</label>
            <input type="text" id="email"><br>
            <label for="">Password</label>
            <input type="text" id="password"><br>
           <button type="button" onclick="claim()">Claim Your Free Trail</button>
           <p>You Are Agreeing to Our <a href="#">Terms & Condition</a></p>
        </form>

        <script>
            function claim(){
                var obj ={
                    fname:"",
                    lname:"",
                    email:"",
                    password:""
                }

                for(a in obj){
                    obj[a]=document.getElementById(a).value
                }
                if(obj.email.match(/@/) != null){

                }else{
                    alert("Please enter Valid Email Address")
                }
                console.log(obj)
            }
        </script>
    </body>
4

3 回答 3

0

只需使用正则表达式即可。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

于 2019-10-16T02:02:22.717 回答
0

您可以使用patterninbuilt验证 HTML 表单

  • [^\d]+- 只允许除数字以外的字符
  • [\dA-Za-z]{8,}- 确保只允许使用数字和字母且至少 8 个字符

<body>
  <form validate>
    <label for="">First Name</label>
    <input type="text" id="fname" pattern="[^\d]+" required><br>
    <label for="">Last Name</label>
    <input type="text" id="lname"><br>
    <label for="">Email</label>
    <input type="email" id="email" required><br>
    <label for="">Password</label>
    <input type="password" id="password" pattern="[\dA-Za-z]{8,}" required><br>
    <button type="submit">Claim Your Free Trail</button>
    <p>You Are Agreeing to Our <a href="#">Terms & Condition</a></p>
  </form>
</body>

于 2019-10-16T02:17:25.177 回答
0

密码验证

我们使用以下正则表达式来确保密码仅包含字母和数字:

/[^A-Za-z0-9]+/g
  • [^] : 匹配任何不在集合中的东西
  • AZ:“A”到“Z”范围内的字符
  • aZ : "a" 到 "z" 范围内的字符
  • 0-9 : "0" 到 "9" 范围内的字符
  • g:全局标志,允许迭代搜索

因此,如果密码包含非字母和数字,则正则表达式返回true

整个密码验证功能如下:

function isValidPassword(password) {
    if (
        typeof password !== "string" ||
        password.length !== 8 ||
        /[^A-Za-z0-9]+/g.test(password)
    ) 
        return false;
    return true;
}

名字验证

我们使用以下正则表达式来检查密码是否包含任何数字:

/[0-9]+/g
  • [] : 匹配集合中的任何东西
  • 0-9 : "0" 到 "9" 范围内的字符
  • g:全局标志,允许迭代搜索

整个名字验证功能如下:

function isValidFirstname(firstname) {
    if (
        typeof firstname !== "string" ||
        /[0-9]+/g.test(firstname)
    ) {
        return false; 
    }
    return true;
}
于 2019-10-16T02:37:39.890 回答