我想在我的验证代码中使用regex,但不知道该把它放在哪里?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我想在我的验证代码中使用regex,但不知道该把它放在哪里?相关的知识,希望对你有一定的参考价值。

我想在我的验证代码中使用regex,但不知道该把它放在哪里?

我的regex验证是针对名字、姓氏、电子邮件地址和密码。

我已经把验证放在名和姓上,但是没有用。

另外,谁能建议对密码字段也进行验证?先谢谢你了。

这是我的代码。

const form = document.querySelector("form");
const input = document.querySelectorAll("input");

form.addEventListener("submit",e =>{
    e.preventDefault();
    // console.log(e)
    
    const firstName = form.firstName.value.trim();
    const lastName = form.lastName.value.trim();
    const email = form.email.value.trim();
    const password = form.password.value.trim();
    const nameReg = /^[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð ,.'-]+$/u;
    const emailReg =/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*/;
    
    
    if (firstName === "" && lastName === "" && email === "" && password === ""){
        first()
        last()
        mail()
        pass()
        border();
    } else if (lastName === "" && email === "" && password === ""){
        last();
        mail();
        pass();
        border();

    }else if (email === "" && password === ""){
        mail();
        pass();
        border();
    }else if (lastName === "" && email === ""){
        last();
        mail()
        border();
    }
    else if (lastName === "" && password === ""){
        last();
        pass();
    }else if(firstName === "" && lastName === ""){
        first();
        last();
        border();
    }
     else  if (firstName === "" && firstName === nameReg){
         first()
         border();

    } else if (lastName === "" && lastName === nameReg){
        last();
        border();
    } else if (email === ""){
         mail();
         border();
    } else if (password === ""){
        pass();
        border();
    }else{
        form.reset();
    }
})
///First Name Text
const first = () =>{
    document.getElementById("firstImg").style.display = "initial";
    document.getElementById("firstName").style.display = "block";
    form.firstName.placeholder = "";
}
// Last name Text
const last = () =>{
    document.getElementById("secondImg").style.display = "initial";
    document.getElementById("secondName").style.display = "block";
    form.lastName.placeholder ="";
}
// Email
const mail = () =>{
    document.getElementById("thirdImg").style.display = "initial";
    document.getElementById("third").style.display = "block";
    form.email.placeholder = "email@example/com";
    form.email.setAttribute("class","placeholder"); 
}
//Password Text
const pass = () =>{
    document.getElementById("fourthImg").style.display = "initial";
    document.getElementById("fourth").style.display = "block";
    form.password.placeholder ="";
}
/// Border for the input fields
const border = () =>{
    input.forEach((field)=>{
        if(field.value === ""){
            field.style.border ="2px solid hsl(0, 100%, 74%)";
        } else{
            field.style.border= "1px solid black";
        }
    }
)};
*,
*:focus,
*::before,
*::after {
  margin: 0;
  padding: 0;
  outline: 0;
  box-sizing: border-box;
}
body{
    background-image:url(../images/bg-intro-desktop.png);
    background-color:  hsl(0, 100%, 74%);
    font-family: 'Poppins', sans-serif;
    height: 100%;
    width: 100%;
}
.grid{
    display: grid;
    grid-template-columns: 33% 40%;
    justify-content: space-evenly;
}
.h2{
    color: white;
    font-weight:bolder;
    font-size: 3.2em;
}
.paragraph{
    color: white;
    font-size: 0.9em;
}
#firstH2{
    margin-bottom: -14px;
}
.box{
    background-color: white;
    border-radius: 10px;
    text-align: center;
    height: auto;
    box-shadow: 0px 9px  rgba(0, 0, 0, 0.2);
}
.firstButton{
    font-family: 'Poppins', sans-serif;
    width: 100%;
    border: 0;
    color: white;
    background-color: hsl(248, 32%, 49%);
    font-size: 1.1em;
    padding: 16px;
    border-radius: 10px;
    box-shadow: 0px 9px  rgba(0, 0, 0, 0.2);
    font-weight: bolder; 
}
.firstButton span{
    font-size: 0.8em;
    font-weight: normal;
}
input {
    font-family: 'Poppins', sans-serif;
    width: 90%;
    padding: 15px;
    font-size: 1em;
    border: 1px solid hsl(246, 25%, 77%);
    border-radius: 5px;
    font-weight: 600;
    color:  hsl(249, 10%, 26%);
}
input:focus{
    font-family: 'Poppins', sans-serif;
    font-size: 1em;
    padding: 15px;
    border: 1px solid black;
    border-radius: 5px;
    font-weight: 600;
    color:  hsl(249, 10%, 26%);
}
input::placeholder{
    font-family: 'Poppins', sans-serif;
    font-weight: 600;
}
.placeholder::placeholder{
    color: hsl(0, 100%, 74%);
}
#greenButton{
    width: 90%;
    border: 0;
    padding: 16px;
    background-color: hsl(154, 59%, 51%);
    border-radius: 10px;
    box-shadow: 0px 5px hsl(154, 65%, 43%);
}
#greenButton span{
    font-family: 'Poppins', sans-serif;
    color: white;
    font-size: 1.3em;
    font-weight: bold;
}
#greenButton:hover{
    cursor: pointer;
    background-color: hsl(154, 94%, 65%);
}
.terms{
    color: hsl(246, 25%, 77%);
    font-size: 12px;
    margin-top: 2%;
    text-align: center;
}
.terms span a{
    text-decoration: none;
    color: hsl(0, 100%, 74%);
    font-weight: bold;
}
form{
    position: relative;
}
#firstImg{
    display: none;
    position: absolute;
    top: 13%;
    right: 9%;
}
#secondImg{
    display: none;
    position: absolute;
    top: 29%;
    right: 9%;
}
#thirdImg{
    display: none;
    position: absolute;
    top: 45%;
    right: 9%;
    
}
#fourthImg{
    display: none;
    position: absolute;
    bottom: 33.5%;
    right: 9%;
}
.errorMessage{
    font-size: 0.8em;
    color: hsl(0, 100%, 74%);
    text-align: right;
    font-style: italic;
    font-weight: 500;
    margin-right: 30px;
    margin-top: -25px;
    margin-bottom: 18px;
}
#firstName{
    display: none;
}
#secondName{
    display: none;
}
#third{
    display: none;
}
#fourth{
    display: none;
}
.attribution{
    font-size: 11px;
    text-align: center;
    color: white;
}
.attribution a {
    color: hsl(228, 45%, 44%);
}

@media only screen and (max-width:700px){
    body{
        background-image:url(../images/bg-intro-mobile.png);
    }
    .grid{
        grid-template-columns: 90%;
    }
    .h2,.paragraph{
        text-align: center;
    }

}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- displays site properly based on user's device -->

  <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
  <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="css/style.css">
  <title>Intro component With Sign up Form</title>


</head>
<body>
  <div class="container">
    <div class="grid">
       <!-- 1st grid -->
        <div>
          <br><br><br><br><br><br><br><br>
          <h2 class="h2" id="firstH2">Learn to code by</h2>
          <h2 class="h2">watching others</h2><br>
          <p class="paragraph">See how experienced solve problems in real time. Watching scripted tutuorials is great, but 
            understanding how developers think is invaluable.</p>
        </div>
         <!-- 2nd grid -->
        <div>
          <div>
            <br><br>
            <button class="firstButton">Try it free 7 days <span>then $20/mo. thereafter</span></button>
            <br><br>
            <!-- box for white color -->
            <div class="box">
              <form>
                <br><br>
                <input type="text" name="firstName" placeholder="First Name"><br><br>
                <img src="../images/icon-error.svg" id="firstImg" alt="error">
                <div class="errorMessage" id="firstName">First Name cannot be empty</div>

                <input type="text" name="lastName" placeholder="Last Name"><br><br>
                <img src="../images/icon-error.svg" id="secondImg" alt="error">
                <div class="errorMessage" id="secondName">Last Name cannot be empty</div>

                <input type="email" name="email" placeholder="Email Address"><br><br>
                <img src="../images/icon-error.svg" id="thirdImg" alt="error">
                <div class="errorMessage" id="third">Looks like this is not an email</div>

                <input type="password" name="password" placeholder="Password"><br><br>
                <img src="../images/icon-error.svg" id="fourthImg" alt="error">
                <div class="errorMessage" id="fourth">Password cannot be empty</div>

                <button type="submit" id="greenButton"><span>CLAIM YOUR FREE TRIAL</span></button><br>

                <div class="terms">
                  By clicking the button you are agreeing to our <span><a href="#">Terms and Services</a></span>
                </div><br><br>
              </form>
            </div>

          </div>
        </div>
    </div>
  </div>

  
  <br><br>
  <footer>
    <p class="attribution">
      Challenge by <a href="https://www.frontendmentor.io?ref=challenge" target="_blank">Frontend Mentor</a>. 
      Coded by <a href="#">Gurkiran Singh</a>.
    </p>
  </footer>
  <script src="js/script.js"></script>
</body>
</html>

这里是 a JSFiddle

答案

这里是一个Corona-times类型的答案。我有太多的时间,所以我坐下来,试着重新修改你的例子。

我的第一印象是:你应该尽量不要重复自己("DRY" : Don't Repeat Yourself)。这既适用于你的HTML,也适用于你的javascript。我删除了不少你的ID,因为它们只会让脚本更难写,更啰嗦。相反,我试着分析你的HTML的结构。我首先扫描你的表单,并将所有的输入字段、图片标签和divs收集到一个叫做 inps. 这是由创建一个 "适当的 "阵列来完成的,通过应用 [... <nodelist>] 的节点列表上,我从 document.querySelectorAll() 呼叫,过滤掉所有

  • <input>
  • <img>
  • 和所有带有 class="errorMessage"

然后,我应用 .reduce() 方法来创建另一个数组(inps,一个对象数组),其中

  • 我首先将对象 {inp:el} 含有 <input> 元素,然后
  • 然后,我将这个 "最新 "对象(a[a.length-1])的进一步属性(imgdiv),其中包含错误的<img> 和错误信息<div>. (注意:只有在以下情况下才会正常工作) 在HTML中为每张图片配上相关的图片和一个错误信息div <input> 字段!)

触发的 submit-事件我就走过这个精心准备的(inps)数组,检查收集到的输入字段的内容,并对相关的图片和div进行必要的操作。在 inps.forEach(e=>...) 我可以用 e.inp 及其相关的错误图像和错误div,并以 e.imge.div.

如前所述,这对我来说是一个 "Corona时代类型的练习",以表明用相对较短的代码是可行的,但我强烈建议使用真正优秀的HTML5方法(使用 minlength 和适当的 type的输入元素!)。)

const frm=document.forms[0]; 
const inps=[...frm.querySelectorAll('input,img,.errorMessage')].reduce((a,el,i)=>{
   if (i%3==0) a.push({inp:el});
   else a[a.length-1][el.tagName.toLocaleLowerCase()]=el;
   return a;
 },[])
// the following is superfluous, as it will always test as positive for <input type="email">:
const emailRX =/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*/;

frm.onsubmit=(ev)=>{
 let err,allerrs=0 
 inps.forEach(e=>{
   allerrs+=err=e.inp.value==''? 1 : e.inp.name=="email" ? ( emailRX.test(e.inp.value) ? 0 : 2 ) : 0;
   e.img.style.display=['none','initial','initial'][err];
   e.div.textContent=['',e.inp.placeholder+' must be filled!','Email appears to be invalid'][err];
 })
 return allerrs==0;
}
*,
*:focus,
*::before,
*::after {
  margin: 0;
  padding: 0;
  outline: 0;
  box-sizing: border-box;
}
body{
    background-image:url(../images/bg-intro-desktop.png);
    background-color:  hsl(0, 100%, 74%);
    font-family: 'Poppins', sans-serif;
    height: 100%;
    width: 100%;
}
.grid{
    display: grid;
    grid-template-columns: 33% 40%;
    justify-content: space-evenly;
}
.h2{
    color: white;
    font-weight:bolder;
    font-size: 3.2em;
}
.paragraph{
    color: white;
    font-size: 0.9em;
}
#firstH2{
    margin-bottom: -14px;
}
.box{
    background-color: white;
    border-radius: 10px;
    text-align: center;
    height: auto;
    box-shadow: 0px 9px  rgba(0, 0, 0, 0.2);
}
.firstButton{
    font-family: 'Poppins', sans-serif;
    width: 100%;
    border: 0;
    color: white;
    background-color: hsl(248, 32%, 49%);
    font-size: 1.1em;
    padding: 16px;
    border-radius: 10px;
    box-shadow: 0px 9px  rgba(0, 0, 0, 0.2);
    font-weight: bolder; 
}
.firstButton span{
    font-size: 0.8em;
    font-weight: normal;
}
input {
    font-family: 'Poppins', sans-serif;
    width: 90%;
    padding: 15px;
    font-size: 1em;
    border: 1px solid hsl(246, 25%, 77%);
    border-radius: 5px;
    font-weight: 600;
    color:  hsl(249, 10%, 26%);
}
input:focus{
    font-family: 'Poppins', sans-serif;
    font-size: 1em;
    padding: 15px;
    border: 1px solid black;
    border-radius: 5px;
    font-weight: 600;
    color:  hsl(249, 10%, 26%);
}
input::placeholder{
    font-family: 'Poppins', sans-serif;
    font-weight: 600;
}
.placeholder::placeholder{
    color: hsl(0, 100%, 74%);
}
#greenButton{
    width: 90%;
    border: 0;
    padding: 16px;
    background-color: hsl(154, 59%, 51%);
    border-radius: 10px;
    box-shadow: 0px 5px hsl(154, 65%, 43%);
}
#greenButton span{
    font-family: 'Poppins', sans-serif;
    color: white;
    font-size: 1.3em;
    font-weight: bold;
}
#greenButton:hover{
    cursor: pointer;
    background-color: hsl(154, 94%, 65%);
}
.terms{
    color: hsl(246, 25%, 77%);
    font-size: 12px;
    margin-top: 2%;
    text-align: center;
}
.terms span a{
    text-decoration: none;
    color: hsl(0, 100%, 74%);
    font-weight: bold;
}
form{
    position: relative;
}
.errorMessage{
    font-size: 0.8em;
    color: hsl(0, 100%, 74%);
    text-align: right;
    font-style: italic;
    font-weight: 500;
    margin-right: 30px;
    margin-top: -25px;
    margin-bottom: 18px;
}
form img {display:none} /* hide all error-img first ... */
.attribution{
    font-size: 11px;
    text-align: center;
    color: white;
}
.attribution a {
    color: hsl(228, 45%, 44%);
}

@media only screen and (max-width:700px){
    body{
        background-image:url(../images/bg-intro-mobile.png);
    }
    .grid{
        grid-template-columns: 90%;
    }
    .h2,.paragraph{
        text-align: center;
    }

}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- displays site properly based on user's device -->

  <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
  <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="css/style.css">
  <title>Intro component With Sign up Form</title>


</head>
<body>
  <div class="container">
    <div class="grid">
       <!-- 1st grid -->
        <div>
          <br><br><br><br><br><br><br><br>
          <h2 class="h2" id="firstH2">Learn to code by</h2>
          <h2 class="h2">watching others</h2><br>
          <p class="paragraph">See how experienced solve problems in real time. Watching scripted tutuorials is great, but understanding how developers think is invaluable.</p>
        </div>
         <!-- 2nd grid -->
        <div>
          <div>
            <br><br>
            <button class="firstButton">Try it free 7 days <span>then $20/mo. thereafter</span></button>
            <br><br>
            <!-- box for white color -->
            <div class="box">
              <form>
                <br><br>
                <input type="text" name="firstName" placeholder="First Name" minlength="3"><br><br>
                <img src="../images/icon-error.svg" alt="error">
                <div class="errorMessage"></div>

                <input type="text" name="lastName" placeholder="Last Name" minlength="3"><br><br>
                <img src="../images/icon-error.svg" alt="error">
                <div class="errorMessage"></div>

                <input type="email" name="email" placeholder="Email Address"><br><br>
                <img src="../images/icon-error.svg" alt="error">
                <div class="errorMessage"></div>

                <input type="password" name="password" placeholder="Password"><br><br>
                <img src="../images/icon-error.svg" alt="error">
                <div class="errorMessage"></div>

                <button type="submit" id="greenButton"><span>CLAIM YOUR FREE TRIAL</span></button><br>

                <div class="terms">
             

以上是关于我想在我的验证代码中使用regex,但不知道该把它放在哪里?的主要内容,如果未能解决你的问题,请参考以下文章

在我的弹出式灯箱中添加外部链接

在 Java 应用程序中使用 NTLM 身份验证

在 VS 代码中保存时美化?

我想在我的PHP网站里加一个验证码,滑动那种

使用 Jquery Validation 验证印度车辆编号的车辆编号

在Laravel项目中放置Crawler脚本的位置?