联系人表单默认值验证


Contact form default value validation

我有一个在网上免费提供的联系表格。谢天谢地,这太棒了,但对于我有默认值(如"全名")的表单,我不知道如何在JS和PHP中验证这些字段。

这是我的HTML:

<input type="text" name="contactname" id="contactname" class="required" role="input" aria-required="true" onfocus="if(this.value=='Full Name') this.value='';" onblur="if(this.value=='') this.value='Full Name';" value="Full Name" />

这是我的JS:

$(document).ready(function(){
// validate signup form on keyup and submit
var validator = $("#contactform").validate({
    rules: {
        contactname: {
            required: true,
            minlength: 2
        },
        email: {
            required: true,
            email: true
        },
        telephone: {
            required: true,
            minlength: 11
        },
        message: {
            required: true,
            minlength: 10
        }
    },
    messages: {
        contactname: {
            required: "Please enter your Full Name",
            minlength: jQuery.format("Your name needs to be at least {0} characters")
        },
        email: {
            required: "Please enter a valid Email Address",
            minlength: "Please enter a valid Email Address"
        },
        telephone: {
            required: "Please enter a valid Telephone Number",
            minlength: "Please enter a valid Telephone Number"
        },
        message: {
            required: "You need to enter details!",
            minlength: jQuery.format("Enter at least {0} characters")
        }
    },
    // set this class to error-labels to indicate valid fields
    success: function(label) {
        label.addClass("checked");
    }
});
});

<?php
//If the form is submitted
if(isset($_POST['contactform'])) {
  //Check to make sure that the name field is not empty
  if(trim($_POST['contactname']) == '') {
      $hasError = true;
  } else {
      $name = trim($_POST['contactname']);
  }
  //Check to make sure sure that a valid email address is submitted
  if(trim($_POST['email']) == '')  {
    $hasError = true;
  } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+'.[A-Z]{2,4}$", trim($_POST['email']))) {
      $hasError = true;
  } else {
      $email = trim($_POST['email']);
  }
  //Check to make sure comments were entered
  if(trim($_POST['message']) == '') {
    $hasError = true;
  } else {
      if(function_exists('stripslashes')) {
          $comments = stripslashes(trim($_POST['message']));
      } else {
          $comments = trim($_POST['message']);
      }
  }
  //If there is no error, send the email
  if(!isset($hasError)) {
      $emailTo = 'email address'; //Put your own email address here
      $subject = 'Contact Form';
      $body = "Full Name: $name 'nEmail Address: $email 'nDetails: $comments";
      $headers = 'From: Company <'.$emailTo.'>' . "'r'n" . 'Reply-To: ' . $email;
      mail($emailTo, $subject, $body, $headers);
      $emailSent = true;
      die(header('Location: index.html'));
  }
}
?>

提前感谢您的帮助!

使用placeholder属性,而不是在字段中放入默认值。

<input type="text" name="contactname" id="contactname" class="required" role="input" aria-required="true" placeholder="Full Name" />

然后,要在IE中启用占位符,请使用以下插件:

// ****** START jQuery Placeholder INTEGRATION ***** //
/* Adds class="placeholder" to input elements in browsers that do not support native placeholder attributes (such as IE 6-9) 
http://mths.be/placeholder v2.0.7 by @mathias
https://github.com/mathiasbynens/jquery-placeholder
 */
;(function(f,h,$){var a='placeholder' in h.createElement('input'),d='placeholder' in h.createElement('textarea'),i=$.fn,c=$.valHooks,k,j;if(a&&d){j=i.placeholder=function(){return this};j.input=j.textarea=true}else{j=i.placeholder=function(){var l=this;l.filter((a?'textarea':':input')+'[placeholder]').not('.placeholder').bind({'focus.placeholder':b,'blur.placeholder':e}).data('placeholder-enabled',true).trigger('blur.placeholder');return l};j.input=a;j.textarea=d;k={get:function(m){var l=$(m);return l.data('placeholder-enabled')&&l.hasClass('placeholder')?'':m.value},set:function(m,n){var l=$(m);if(!l.data('placeholder-enabled')){return m.value=n}if(n==''){m.value=n;if(m!=h.activeElement){e.call(m)}}else{if(l.hasClass('placeholder')){b.call(m,true,n)||(m.value=n)}else{m.value=n}}return l}};a||(c.input=k);d||(c.textarea=k);$(function(){$(h).delegate('form','submit.placeholder',function(){var l=$('.placeholder',this).each(b);setTimeout(function(){l.each(e)},10)})});$(f).bind('beforeunload.placeholder',function(){$('.placeholder').each(function(){this.value=''})})}function g(m){var l={},n=/^jQuery'd+$/;$.each(m.attributes,function(p,o){if(o.specified&&!n.test(o.name)){l[o.name]=o.value}});return l}function b(m,n){var l=this,o=$(l);if(l.value==o.attr('placeholder')&&o.hasClass('placeholder')){if(o.data('placeholder-password')){o=o.hide().next().show().attr('id',o.removeAttr('id').data('placeholder-id'));if(m===true){return o[0].value=n}o.focus()}else{l.value='';o.removeClass('placeholder');l==h.activeElement&&l.select()}}}function e(){var q,l=this,p=$(l),m=p,o=this.id;if(l.value==''){if(l.type=='password'){if(!p.data('placeholder-textinput')){try{q=p.clone().attr({type:'text'})}catch(n){q=$('<input>').attr($.extend(g(this),{type:'text'}))}q.removeAttr('name').data({'placeholder-password':true,'placeholder-id':o}).bind('focus.placeholder',b);p.data({'placeholder-textinput':q,'placeholder-id':o}).before(q)}p=p.removeAttr('id').hide().prev().attr('id',o).show()}p.addClass('placeholder');p[0].value=p.attr('placeholder')}else{p.removeClass('placeholder')}}}(this,document,jQuery));
$(document).ready(function() {
    $('input, textarea').placeholder();
});
// ****** END jQuery Placeholder INTEGRATION ***** //

更新

以下是IE占位符集成:http://jsfiddle.net/DNX8V/1/

验证对我来说似乎很有效。。。?

更新#2

将电子邮件验证替换为:

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^((([a-z]|'d|[!#'$%&''*'+'-'/='?'^_`{'|}~]|['u00A0-'uD7FF'uF900-'uFDCF'uFDF0-'uFFEF])+('.([a-z]|'d|[!#'$%&''*'+'-'/='?'^_`{'|}~]|['u00A0-'uD7FF'uF900-'uFDCF'uFDF0-'uFFEF])+)*)|(('x22)(((('x20|'x09)*('x0d'x0a))?('x20|'x09)+)?((['x01-'x08'x0b'x0c'x0e-'x1f'x7f]|'x21|['x23-'x5b]|['x5d-'x7e]|['u00A0-'uD7FF'uF900-'uFDCF'uFDF0-'uFFEF])|(''(['x01-'x09'x0b'x0c'x0d-'x7f]|['u00A0-'uD7FF'uF900-'uFDCF'uFDF0-'uFFEF]))))*((('x20|'x09)*('x0d'x0a))?('x20|'x09)+)?('x22)))@((([a-z]|'d|['u00A0-'uD7FF'uF900-'uFDCF'uFDF0-'uFFEF])|(([a-z]|'d|['u00A0-'uD7FF'uF900-'uFDCF'uFDF0-'uFFEF])([a-z]|'d|-|'.|_|~|['u00A0-'uD7FF'uF900-'uFDCF'uFDF0-'uFFEF])*([a-z]|'d|['u00A0-'uD7FF'uF900-'uFDCF'uFDF0-'uFFEF])))'.)+(([a-z]|['u00A0-'uD7FF'uF900-'uFDCF'uFDF0-'uFFEF])|(([a-z]|['u00A0-'uD7FF'uF900-'uFDCF'uFDF0-'uFFEF])([a-z]|'d|-|'.|_|~|['u00A0-'uD7FF'uF900-'uFDCF'uFDF0-'uFFEF])*([a-z]|['u00A0-'uD7FF'uF900-'uFDCF'uFDF0-'uFFEF])))'.?$/i);
    return pattern.test(emailAddress);
};

然后

if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here */ }