简体   繁体   中英

Why my Javascript input validation doesn't want to run?

I am a beginner in javascript so I already have some issues at the beginning. It is about input validation where for some reason my alert function doesn't want to run.

Here is HTML code or input section:

 const txtName = document.querySelector("#name"); const btnNotify = document.querySelector("#btn-notify"); const msgText = document.querySelector("#.text"); const msgTexttwo = document.querySelector("#.texttwo") const mailFormat = /^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/; btnNotify.addEventListener('click', () => { if(txtName.value.match(mailFormat) ) { msgText.classList.add('hide'); msgTexttwo.classList.add('hide'); txtName.removeAttribute('style') }else { msgText.classList.add('hide'); msgTexttwo.classList.add('hide'); txtName.setAttribute('style', 'border: 2px solid red;'); } });
 <div class="input"> <input id="name" class="error" type="email" placeholder="Your email address..."> <span class="text hide">Please provide valid email address</span> <span class="texttwo hide">Please provide valid email address</span> <a id="btn-notify" class="click" href="">Notify Me</a> </div>

to get a class you have to use '.' and '#' for id you are using both of them const msgText = document.querySelector("#.text"); const msgTexttwo = document.querySelector("#.texttwo")

here is a correction of your code

 const txtName = document.querySelector("#name"); const btnNotify = document.querySelector("#btn-notify"); const msgText = document.querySelector(".text"); const msgTexttwo = document.querySelector(".texttwo") const mailFormat = /^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/; btnNotify.addEventListener('click', () => { if(txtName.value.match(mailFormat) ) { msgText.classList.add('hide'); msgTexttwo.classList.add('hide'); txtName.removeAttribute('style') }else { msgText.classList.add('hide'); msgTexttwo.classList.add('hide'); txtName.setAttribute('style', 'border: 2px solid red;'); } });
 <div class="input"> <input id="name" class="error" type="email" placeholder="Your email address..."> <span class="text hide">Please provide valid email address</span> <span class="texttwo hide">Please provide valid email address</span> <a id="btn-notify" class="click" href="#">Notify Me</a> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM