简体   繁体   中英

Create the login and validate email address

I want to create a login page in JavaScript and here is the wrong code. All I want is that when I enter a wrong email address, it should show an alert when I left it blank then it show an alert.

 function check(form) { if (form.email.value == "id@gmail.com") { alert("correct username") } else if (form.email.value == "") { alert("blank username") } var email = document.getElementById('email'); var filter = /^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/; if (!filter.test(email.value)) { alert('Please provide a valid email address'); email.focus; return false; } } else if (form.pswrd.value == "123") { alert("correct details") } else if (form.pswrd.value == "") { alert("blank password") } } 
 <h1>Login </h1> <form name="login"> Username <input type="text" name="email"/> Password <input type="password" name="pswrd"/> <input type="button" onclick="check(this.form)" value="Login"/> <input type="reset" value="reset"/> </form> 

Mistakes:

  1. You are not supposed to use <script> tags inside JavaScript. They are invalid.
  2. You haven't given an id="email" to the input . So that doesn't work.
  3. Add an else part for email validation.
  4. Separate your password check from the email check if...else block.

Working Snippet

 function check(form) { if (form.email.value == "id@gmail.com") { alert("correct username") } else if (form.email.value == "") { alert("blank username") } else if (form.email.value != "") { var email = document.getElementById('email'); var filter = /^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/; if (!filter.test(email.value)) { alert('Please provide a valid email address'); email.focus; return false; } } if (form.pswrd.value == "123") { alert("correct details") } else if (form.pswrd.value == "") { alert("blank password") } } 
 <h1>Login </h1> <form name="login"> Username <input type="text" name="email" id="email" /> Password <input type="password" name="pswrd"/> <input type="button" onclick="check(this.form)" value="Login" /> <input type="reset" value="reset"/> </form> 

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