验证输入字段是否有正确的电子邮件ID?

时间:2014-07-14 08:10:59

标签: forms input-field

我想在联系表单中提供帮助。当用户在输入字段&中输入他的电子邮件ID时,我希望这样如果它是错的,即没有@,输入框应该摇动(这表示错误)&当用户输入正确的电子邮件ID时,它应该接受它。

我当前代码中的问题是,当用户输入正确的电子邮件ID时,即使这样输入字段也会抖动。需要验证输入字段以获取正确的电子邮件。

任何帮助将不胜感激。

提前致谢。

<form id="form_id" method="post" action="<?php $_SERVER['PHP_SELF'] ?>" onsubmit="javascript:return validate('form_id','email');" novalidate>

<input type="text" id="email" name="email"   value="<?php if (isset($_POST["email"])) {echo $ema;} ?>" class="error"/> 
 <br><br>
<button type="submit" name="submit" class="getaccess-btn">Get Access </button>

</form>

同样的js是:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script language="javascript">
function validate(form_id,email) {
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
  var address = document.forms[form_id].elements[email].value;
if(reg.test(address) == false) {


$(document).ready(function(){
 $("button").click(function(){
$("#email").delay(0).animate({"left": "-=30px"}, 80).animate({"left": "+=60px"}, 80).animate({"left": "-=60px"}, 80).animate({"left": "+=60px"}, 80).animate({"left": "-=30px"}, 80);
 });
});
return false;
}}
</script>

这个PHP代码

<?php



$your_email = "youremailid@gmail.com"; // email address to which the form data will be sent
$subject = "Contact Message"; // subject of the email that is sent
$thanks_page = "thank-you.html"; // path to the thank you page following successful form submission

// Nothing needs to be modified below this line

if (isset($_POST["submit"])) {

    $ema = trim($_POST["email"]);
    if (get_magic_quotes_gpc()) { 
    $ema = stripslashes($ema);
    }

$error_msg=array(); 

if (empty($ema) || !filter_var($ema, FILTER_VALIDATE_EMAIL)) {
    $error_msg[] = "Your email must have a valid format, such as name@mailhost.com";
}

$email_body = 
    "Email of sender: $ema\n\n" .
    "$com" ; 

// Assuming there's no error, send the email and redirect to Thank You page

if  (!$error_msg) {
mail ($your_email, $subject, $email_body, "From: $nam <$ema>" . "\r\n" . "Reply-To:");
header ("Location: $thanks_page");
exit();
}  

} 

&GT;

同样的css是:

.error{height:auto;width:100px;position:absolute;}

1 个答案:

答案 0 :(得分:0)

我无法正确理解您的问题,但如果您正在使用电子邮件验证,则无需使用javascript。您只需在email中使用input type作为HTML5

对于ex,您可以写如下:

<form>
    <input type="email" name="email" required>

    <input type="submit">

</form>

这将自动验证@.的输入字段。

fiddle is here