JavaScript客户端验证无效

时间:2018-05-08 05:40:10

标签: javascript html

我设计了一个登录页面,但客户端验证无效。我编写了用于验证的JavaScript代码。如何使电子邮件扩展接受只是特定的comp。例如:user@example.com。它应该只接受example.com电子邮件ID。我试图在JavaScript验证中提供扩展名:“example.com”,但它无效。

代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <!-- This file has been downloaded from Bootsnipp.com. Enjoy! -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
    <meta charset="utf-8">
    <!-- Font CSS (Via CDN) -->
    <link rel='stylesheet' type='text/css' href='http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700'>
    <!-- Favicon -->
    <link rel="shortcut icon" href="img/favicon.ico">
    <!--Table container---->
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="css/login.css" rel="stylesheet">
    <script src="js/ValidationFormScript.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
  </head>
  <nav class="navbar navbar-light" style="background-color: #e3f2fd;">
    <!-- Navbar content -->
  </nav>
  <!---Body starts here---->
  <body>
    <br><br><br><br>
    <section class="login-block">
      <div class="container">
      <div class="row">
        <div class="col-sm-12 col-md-8 banner-sec">
          <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
            <div class="carousel-inner" role="listbox">
              <div class="carousel-item active">
                <img class="img-fluid" src="img/logo.jpg" alt="First slide">
              </div>
            </div>
          </div>
        </div>
        <div class="col-sm-12 col-md-4 login-sec">
          <!---Break line after header ---->
          <br />
          <!--- Form starts here----->
          <form class="login-form" method="" action="" id="admin-form">
            <!---- Starts the User ID section--->
            <div class="form-group">
              <label for="exampleInputEmail" class="text-left"><span>User ID</span></label>
              <span class="input-status" data-toggle="tooltip" data-placement="top"  title="Input your email"></span>
              <input type="email" class="form-control" id="email" name="email" placeholder="enter email">
            </div>
            <!---- Starts the Password section--->
            <div class="form-group">
              <label for="exampleInputPassword" class="text-left"><span>Password</span></label>
              <span class="input-status" data-toggle="tooltip" data-placement="top"  title="Input your password"></span>
              <input type="password" class="form-control" name="password" id="password"  placeholder="enter password">
            </div>
            <!---- Ends the Password section--->
            <!---Submit button--->
            <div class="form-group">
              <button type="submit" class="btn btn-login float-right">Login</button>
            </div>
          </form>
        </div>
      </div>
    </section>
    <!----- Script for Validation----->
    <!-- jQuery Validate Plugin-->
    <script src="js/jquery.validate.min.js"></script>
    <script type="text/javascript">
      jQuery(document).ready(function() {
      
        "use strict";
      
        // Init Theme Core    
        Core.init();
      
        // Init Demo JS     
        Demo.init();
      
        /* @custom validation method (smartCaptcha) 
        ------------------------------------------------------------------ */
      
        $.validator.methods.smartCaptcha = function(value, element, param) {
          return value == param;
        };
      
        $("#admin-form").validate({
      
          /* @validation states + elements 
          ------------------------------------------- */
      
          errorClass: "state-error",
          validClass: "state-success",
          errorElement: "em",
      
          /* @validation rules 
          ------------------------------------------ */
      
          rules: {
            firstname: {
              required: true
            },
            lastname: {
              required: true
            },
            email: {
              required: true,
              email: true,
        extension: ""
            },
            website: {
              required: true,
              url: true
            },
            language: {
              required: true
            },
            upload1: {
              required: true,
              extension: "jpg|png|gif|jpeg|doc|docx|pdf|xls|rar|zip"
            },
            mobileos: {
              required: true
            },
            comment: {
              required: true,
              minlength: 30
            },
            mobile_phone: {
              require_from_group: [1, ".phone-group"]
            },
            home_phone: {
              require_from_group: [1, ".phone-group"]
            },
            password: {
              required: true,
                      },
            repeatPassword: {
              required: true,
              minlength: 6,
              maxlength: 16,
              equalTo: '#password'
            },
            gender: {
              required: true
            },
            languages: {
              required: true
            },
            verification: {
              required: true,
              smartCaptcha: 19
            },
            applicant_age: {
              required: true,
              min: 16
            },
            licence_no: {
              required: function(element) {
                return $("#applicant_age").val() > 19;
              }
            },
            child_name: {
              required: "#parents:checked"
            }
      
          },
      
          /* @validation error messages 
          ---------------------------------------------- */
      
          messages: {
            firstname: {
              required: 'Enter first name'
            },
            lastname: {
              required: 'Enter last name'
            },
            useremail: {
              required: 'Enter email address',
              email: 'Enter a VALID email address'
            },
            website: {
              required: 'Enter your website URL',
              url: 'URL should start with - http://www'
            },
            language: {
              required: 'Choose a language'
            },
            upload1: {
              required: 'Please browse a file',
              extension: 'File format not supported'
            },
            mobileos: {
              required: 'Please select a mobile platform'
            },
            comment: {
              required: 'Oops you forgot to comment',
              minlength: 'Enter at least 30 characters or more'
            },
            mobile_phone: {
              require_from_group: 'Fill at least a mobile contact'
            },
            home_phone: {
              require_from_group: 'Fill at least a home contact'
            },
            password: {
              required: 'Please enter a password'
            },
            repeatPassword: {
              required: 'Please repeat the above password',
              equalTo: 'Password mismatch detected'
            },
            gender: {
              required: 'Please choose specie'
            },
            languages: {
              required: 'Select laguages spoken'
            },
            verification: {
              required: 'Please enter verification code',
              smartCaptcha: 'Oops - enter a correct verification code'
            },
            applicant_age: {
              required: 'Enter applicant age',
              min: 'Must be 16 years and above'
            },
            licence_no: {
              required: 'Enter licence number'
            },
            child_name: {
              required: 'Please enter your childs name'
            }
      
          },
      
          /* @validation highlighting + error placement  
          ---------------------------------------------------- */
      
          highlight: function(element, errorClass, validClass) {
            $(element).closest('.field').addClass(errorClass).removeClass(validClass);
          },
          unhighlight: function(element, errorClass, validClass) {
            $(element).closest('.field').removeClass(errorClass).addClass(validClass);
          },
          errorPlacement: function(error, element) {
            if (element.is(":radio") || element.is(":checkbox")) {
              element.closest('.option-group').after(error);
            } else {
              error.insertAfter(element.parent());
            }
          }
      
        });
      
      
        // Cache several DOM elements
        var pageHeader = $('.content-header').find('b');
        var adminForm = $('.admin-form');
        var options = adminForm.find('.option');
        var switches = adminForm.find('.switch');
        var buttons = adminForm.find('.button');
        var Panel = adminForm.find('.panel');
      
        // Form Skin Switcher
        $('#skin-switcher a').on('click', function() {
          var btnData = $(this).data('form-skin');
      
          $('#skin-switcher a').removeClass('item-active');
          $(this).addClass('item-active')
      
          adminForm.each(function(i, e) {
            var skins = 'theme-primary theme-info theme-success theme-warning theme-danger theme-alert theme-system theme-dark'
            var panelSkins = 'panel-primary panel-info panel-success panel-warning panel-danger panel-alert panel-system panel-dark'
            $(e).removeClass(skins).addClass('theme-' + btnData);
            Panel.removeClass(panelSkins).addClass('panel-' + btnData);
            pageHeader.removeClass().addClass('text-' + btnData);
          });
      
          $(options).each(function(i, e) {
            if ($(e).hasClass('block')) {
              $(e).removeClass().addClass('block mt15 option option-' + btnData);
            } else {
              $(e).removeClass().addClass('option option-' + btnData);
            }
          });
      
          // var sliders = $('.ui-timepicker-div', adminForm).find('.ui-slider');
          $('body').find('.ui-slider').each(function(i, e) {
            $(e).addClass('slider-primary');
          });
      
          $(switches).each(function(i, ele) {
            if ($(ele).hasClass('switch-round')) {
              if ($(ele).hasClass('block')) {
                $(ele).removeClass().addClass('block mt15 switch switch-round switch-' + btnData);
              } else {
                $(ele).removeClass().addClass('switch switch-round switch-' + btnData);
              }
            } else {
              if ($(ele).hasClass('block')) {
                $(ele).removeClass().addClass('block mt15 switch switch-' + btnData);
              } else {
                $(ele).removeClass().addClass('switch switch-' + btnData);
              }
            }
      
          });
          buttons.removeClass().addClass('button btn-' + btnData);
        });
      
        setTimeout(function() {
          adminForm.addClass('theme-primary');
          Panel.addClass('panel-primary');
          pageHeader.addClass('text-primary');
      
          $(options).each(function(i, e) {
            if ($(e).hasClass('block')) {
              $(e).removeClass().addClass('block mt15 option option-primary');
            } else {
              $(e).removeClass().addClass('option option-primary');
            }
          });
      
          // var sliders = $('.ui-timepicker-div', adminForm).find('.ui-slider');
          $('body').find('.ui-slider').each(function(i, e) {
            $(e).addClass('slider-primary');
          });
      
          $(switches).each(function(i, ele) {
            if ($(ele).hasClass('switch-round')) {
              if ($(ele).hasClass('block')) {
                $(ele).removeClass().addClass('block mt15 switch switch-round switch-primary');
              } else {
                $(ele).removeClass().addClass('switch switch-round switch-primary');
              }
            } else {
              if ($(ele).hasClass('block')) {
                $(ele).removeClass().addClass('block mt15 switch switch-primary');
              } else {
                $(ele).removeClass().addClass('switch switch-primary');
              }
            }
          });
          buttons.removeClass().addClass('button btn-primary');
        }, 800);
      
      
      
      });
    </script>
  </body>
</html>

<style type="text/css">
        @import url("//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css");
.login-block{
    background: #fff;  /* fallback for old browsers */
background: -webkit-linear-gradient(to bottom, #fff, #fff);  /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to bottom, #fff, #fff); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
float:left;
width:100%;
padding : 50px 0;
}
.banner-sec{background:#fff;  no-repeat left bottom; background-size:cover; min-height:0px; border-radius: 0 10px 10px 0; padding:0;}

.carousel-inner{border-radius:10px 10px 10px 10px;}
}
.login-sec{padding: 60px 30px; position:relative;}
.login-sec .copy-text{position:absolute; width:100%; bottom:20px; font-size:13px; text-align:left;}
.login-sec .copy-text i{color:#FEB58A;}
.login-sec .copy-text a{color:#E36262;}
.login-sec h2{margin-bottom:30px; font-weight:400; font-size:30px; color: grey;}
.btn-login{background: #90EE90; color:#000; font-weight:400;}
.banner-text{width:70%; position:absolute; bottom:40px; padding-left:20px;}
.banner-text p{color:#fff;}
.carousel-caption {
    position: absolute;
    left: 3%;
    right: 26%;
    bottom: 160px;
    z-index: 10;
    padding-top: 20px;
    padding-bottom: 20px;
    color: #ffffff;
    text-align: center;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
	font: Century Gothic;
	font-weight: 400;
}

body {
    font-family: "Helvetica Neue",Century Gothic,Century Gothic,Century Gothic;
    font-size: 14px;
    line-height: 1.428571429;
    color: grey;
    background-color: #fff;
}
	.palel-primary
	{
		border-color: #bce8f1;
	}
	.panel-primary>.panel-heading
	{
		background:#bce8f1;
		
	}
	.panel-primary>.panel-body
	{
		background-color: #EDEDED;
	}
	
	input {
    margin-top: 5px;
    margin-bottom: 5px;
    display:inline-block; 
    *display: inline;     /* for IE7*/
    zoom:1;              /* for IE7*/
    vertical-align:middle;
    margin-left:20px
}

label {
    display:inline-block;
    *display: inline;     /* for IE7*/
    zoom:1;              /* for IE7*/
    float: left;
    padding-top: 5px;
    text-align: right;
    width: 80px;
}
	.form-control {
    display: block;
    width: 77%;
    height: 32px;
	}
	.label{
	color: black;
	}
	label span { color: black; 
	font-weight: normal !important;}
	
	a {
    text-decoration: none !important;
}
body {
    margin-bottom:50px;
}
    </style>

用于验证的JavaScript代码,但它不起作用。

3 个答案:

答案 0 :(得分:1)

您需要添加一个名为'pattern'的属性(基于正则表达式)。它应该看起来像,

<input type="email" class="form-control" id="email" name="email" placeholder="enter email" pattern="[a-zA-Z0-9.!#$%&amp;’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+"/>

或者,您也可以使用事件处理程序属性(如oninput,onvalid,...)发布自定义错误消息。它带来了价值,有助于指导用户更精确和更精确。有意义的消息。

答案 1 :(得分:0)

如果仅打算使用电子邮件输入进行验证,最好使用javascript来验证输入并显示错误消息。

function checkRegistration() {
    var email = document.getElementById('login-email').value;
    var alertMessage = document.getElementById('alert-email');
    var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    var isValid = re.test(email);
    if (isValid) {
      alertMessage.innerHTML = '';
      alertMessage.style.opacity = 0;
      alertMessage.style.visibility = 'hidden';
    }  else { 
      alertMessage.innerHTML = "You have entered an invalid email address!";
      alertMessage.style.opacity = 1;
      alertMessage.style.visibility = 'visible';
    }
    return isValid;
}
#alert-email {
  visibility:hidden;
  opacity:0;
  transition:visibility 0s linear,opacity 0.5s linear;
}
<form onsubmit="return checkRegistration()">
  <div>
    <label>User ID</label>
    <input type="email" placeholder="enter email" id="login-email" />
  </div>
  <span id="alert-email"></span>
  <div>
    <label>Password</label>
    <input type="password"  placeholder="enter password" id="login-password" />
  </div>
  <button type="submit" class="btn btn-login float-right">Login</button>
</form> 

答案 2 :(得分:0)

尝试为JQuery验证添加新要求:

 $.validator.addMethod("email_domain", function (value, element) {
    var regex = /^[a-zA-Z0-9_.+-]+@(?:(?:[a-zA-Z0-9-]+\.)?[a-zA-Z]+\.)?(domain|domain2)\.com$/;
    if(!regex.test(value)) {
       return false;
    }else{
      return true;
    }
 });

然后在表单中添加“电子邮件域”以要求验证