如何用Javascript验证?

时间:2015-10-03 05:38:37

标签: javascript html5 validation

由于必须工作这么多,我对JavaScript完全感到困惑。我已经尝试了很多东西,甚至没有让我的表格验证过一次。我必须使用纯JavaScript来:

**验证电子邮件 - 电子邮件必须包含@,域名应为yahoo.com

电话号码:必须包含10位数字

年龄:必须是小于120的正数

验证应在用户提交表单时进行。如果上述任何验证失败,相应的字段应以红色突出显示

如果验证成功,页面应重定向到http://yahoo.com **

我不是在找人必须给我一个确切的答案,但要把我推向正确的方向,因为我对JS有基本的了解。

    <!DOCTYPE HTML>

<div id="form">

<form name="myForm" action="http://fsu.edu" onsubmit="return validateForm()" method="post">

<head>

<link rel="stylesheet" HREF="C:\Users\Neshia\Desktop\CGS3066\Form Validation Style Sheet.css" TYPE="text/css">

<script>

 function ValidatemyForm()
 {
 var email = document.myForm.email;
 var phone = document.myForm.phonenumber;
 var age = document.myForm.age;
 }

 {
 age = age.replace(/[^0-9]/g, '');
if(age.length != 10) 
{ 
   alert("not 10 digits");
} 
else {
  alert("yep, its 10 digits");
} 
}


 </script>


 </head>

<div id="header">

<hr id="HR1">

<h1> Web Programming: Assignment 3 </h1>

<p> Form Validation with Javascript </p>

<hr id="HR2">

</div>

 <div id="input">

First name: <br>
<input type="text" name="firstname">

<br>

Last name: <br>
<input type="text" name="lastname">

<br>

FSU Email: <br>
<input type= "text" name="email">

<br>

Phone No.: <br>
<input type="numbers" name="phonenumber">

<br>

Age: <br>
<input type="numbers" name="age">

</div>

<hr id="HR3">

<br>

<div id="Sex">

Sex: <br>
    <input type="radio" name="sex" value="male"> Male

<br>

    <input type="radio"  name="sex" value="female"> Female

<br>

    <input type="radio" name="sex" value="other"> Other

</div>

<hr id="HR32">

<div id="languages">

Programming languages you want to learn: <br>

    <input type="checkbox" name="python" value="python"> Python

<br>

    <input type="checkbox" name="java" value="java"> Javascript

<br>

    <input type="checkbox" name="C++" value="C++"> C++

<br>

    <input type="checkbox" name="lisp" valie="lisp"> Lisp

</div>

<hr id="HR32">

<div id="submit">

<input type="Submit" value="Submit">

</div>

<hr id="HR12">


</form>
</div>

3 个答案:

答案 0 :(得分:3)

Aneshia,

你有一些问题。首先是&#34; onsubmit&#34;中列出的功能。表单的属性与您的javascript函数不匹配。你的{}括号也有一些问题。修复后,请务必在表单元素后调用.value以获取输入的值即。 (document.myForm.email。的)。

以下是包含一些修复的代码:

<form name="myForm" onsubmit="return validateForm()" method="post">

<head>

<link rel="stylesheet" HREF="C:\Users\Neshia\Desktop\CGS3066\Form Validation Style Sheet.css" TYPE="text/css">

<script>

 function validateForm() {
  var email = document.myForm.email.value;
  var phone = document.myForm.phonenumber.value;
  var age = document.myForm.age.value;
  console.log(age)

  var okToSubmit = true;
  age = age.replace(/[^0-9]/g, '');
  if (age.length != 10) { 
    alert("not 10 digits");
    okToSubmit = false;
  } else {
    alert("yep, its 10 digits");
  }

  if (age > 120 || age < 0) {
    alert("Must be a positive number less than 120");
    okToSubmit = false;
  }

  return okToSubmit;
}

另一件可能有用的事情是在浏览器中启动javascript控制台并通过键入&#39; validateForm();&#39;

在控制台中手动运行您的功能

答案 1 :(得分:2)

您可能会注意到html5现在验证了其中一些表单,因此您不需要使用Javascript。

请参阅HTML Form Validation

您询问了有关电子邮件,年龄和电话的信息。

考虑以下示例::

&#13;
&#13;
<form>
    <input type="email" name="email" pattern=".*@yahoo\.com"> <br>
    <input type="number" min="18" max="120" name="age"> <br>
    <input type="tel" name="phonenumber"> <br>
    <input type='submit'> 
</form>
&#13;
&#13;
&#13;

如果您想要字段,可以使用

&#13;
&#13;
<form>
    <input type="email" name="email" pattern=".*@yahoo\.com" required> <br>
    <input type="number" min="18" max="120" name="age" required> <br>
    <input type="tel" name="phonenumber" required> <br>
    <input type='submit'> 
</form>
&#13;
&#13;
&#13;

请参阅http://diveintohtml5.info/forms.html

几天后的评论中,你提到需要在Javascript中执行此操作。我认为最好的方法仍然是使用HTML5和一个聪明的方法来做到这一点,如果你必须使用javascript可能是通过javascript设置输入属性。这样的事情可以让你开始逻辑。

虽然我一般不喜欢在代码中明确这一点,但我评论的内容让您可以全面了解如何使用中的数据。

&#13;
&#13;
function validate(event){
  
    // First we stop the form from even submitting until we run the code below
    event.stopPropagation();
  
    // Here we are going to place a reference to the objects we want to validate in an array
    var references = ['email','age','phonenumber'];
    
    // Now we are going to grab our list of inputs from the page
    var inputs = document.getElementsByTagName('input');
    
    // We run through a for loop to look for specific elements
    for(i = 0; i < inputs.length; i++){
      
        /*
        This line simply asks, is the 'name' of this element inside our references array. 
        This works by using the indexOf function which is built into Javascript. 
        indexOf simply provides the index where it finds the phrase you are looking for. 
        In this example, we are using it to see if an index exists by checking it against negative 1
        */
        if(references.indexOf(inputs[i].getAttribute('name')) > -1){
          
            // A switch block lets you present a different outcome based on the criteria being looked for
            switch(inputs[i].getAttribute('name')){
                
                // In this case we see if we get an email named element
                case 'email':
                
                    // We set the attributes to match our requirements for this email element and so on through this switch block for age and phonennumber
                    inputs[i].setAttribute('type','email');
                    inputs[i].setAttribute('pattern','.*@yahoo\.com');
                break;
                case 'age':
                    inputs[i].setAttribute('type','number');
                    inputs[i].setAttribute('min',18);
                    inputs[i].setAttribute('max',120);
                break;
                case 'phonenumber':
                    inputs[i].setAttribute('type','tel');
                break;
            }
          
            // When we are all done, we set the elements to be required
            inputs[i].setAttribute('required',true);
        }
    }
  
    // Now we submit the form
    event.submit();
}
&#13;
<form>
    <input type="text" name="email"> <br>
    <input type="text" name="age"> <br>
    <input type="text" name="phonenumber"> <br>
    <input type='submit' onclick='validate(event)'> 
</form>
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='Javascript:checkEmail();'/>

<script language="javascript">

    function checkEmail() {

        var email = document.getElementById('txtEmail');
        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;
        }
    }

</script>