电子邮件网站和电话号码的表单验证

时间:2013-02-22 20:25:56

标签: javascript html validation

我在这里做错了吗?我正在尝试使用javascript运行一小段验证bny。我正确地做正则表达式吗?

var z=document.forms["myForm"]["website"].value;
if (z==null || z=="")
  {
  $('.five').show();
  return false;
  }
var validWebsite = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
if(!validWebsite.test(document.forms["myForm"]["website"].value))
{
  $('.five').html('Enter a Valid Website');
  return false;
}

var number = /^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/
if(!number.test(document.forms["myForm"]["number"].value)){
    $('.six').show()
    return false;
}

HTML

*email: <br>
<input type="text" name="email"/><div class="four alertmessage" style="display:none;color:red;">Enter your Email</div><br>
website: <br>
<input type="text" name="website"/><div class="five alertmessage" style="display:none;color:red;">Enter your Website</div><br>
Contact phone number: <br>
<input type="text" name="number"/><div class="six alertmessage" style="display:none;color:red;">Enter your Number</div>

<input name="submit" class="submitButton" type="submit" value="Submit">

2 个答案:

答案 0 :(得分:0)

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function validate()
{
    var z=document.forms["myForm"]["website"].value;
    if (z=="")
    {
        $('.five').show();
        return false;
    }

    var validWebsite = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
    if(!validWebsite.test(z)){
        $('.five').html('Enter a Valid Website');
        return false;
    }

    var n=document.forms["myForm"]["number"].value;
    var number = /^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/;
    if(!number.test(n)){
    $('.six').show()
    return false;
    }

    return true;
}
</script>

<form onsubmit="return validate()" method="post" name="myForm"> 
*email: <br>
<input type="text" name="email"/><div class="four alertmessage" style="display:none;color:red;">Enter your Email</div><br>
website: <br>
<input type="text" name="website"/><div class="five alertmessage" style="display:none;color:red;">Enter your Website</div><br>
Contact phone number: <br>
<input type="text" name="number"/><div class="six alertmessage" style="display:none;color:red;">Enter your Number</div>

<input name="submit" class="submitButton" type="submit" value="Submit">
</form>

答案 1 :(得分:0)

您可以参考此链接JQuery form validation