单击提交时如何在文本框中显示错误?

时间:2015-11-14 15:11:18

标签: jquery html

<script>

    var form = $("#contact_form");
    var FName = $("#fname"); //Creates Variables from forms 
    var FNameInfo = $("#fnameInfo");
    var Tele = $("#tele"); 
    var TeleInfo = $("#teleInfo"); 
    var Email = $("#email");
    var EmailInfo = $("#EmailInfo"); 
    var regexp = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_.-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9.]+.[a-z]{2,4}$/; //ragex code 


    FName.blur(validateFName);  //blur is a method which attaches a functiom to run when an event occurs
    Email.blur(validateEmail); 
    Tele.blur(validateTele);
    form.submit (function(){

        //If it passes all of these then return true
        if (validateFName & validateEmail & validateTele() & validateEmail()){ 
            return true;    
        }
        else
        {
            return false;        
        }

    }); 

    //Creates function for Name Validation+
    function validateFName (){

        //If name is length is less than 5 
        if (FName.val().length < 5){

            FName.addClass("error");  //Display error 
            FNameInfo.text("Please Enter Correct Name"); //Changes span name 
            FNameInfo.addClass("error");  //Same error 
            FNameInfo.removeClass("Valid");   

            return false; 

        }
        else{

            FName.removeClass("error");   //remove error class 
            FNameInfo.addClass("Valid") 
            FNameInfo.text("Thanks Buddy" );  //When user enters correct code this text will appear 
            FNameInfo.removeClass("error"); 

            return true;

        }        
    }

    //this function validates Email 
    function validateEmail (){

        var a = $("#email").val (); //Variable a = to input in email 

        if (regexp.test(a)){      //if the input matches the regex code it is valid 

            Email.removeClass("error"); //remove class error as it is not needed 
            EmailInfo.removeClass("error"); 
            EmailInfo.addClass("Valid"); 
            EmailInfo.text("Thankyou"); 
            return true;

        }else{

            Email.addClass("error");    //If its not valid than the error will occur 
            EmailInfo.text("Enter a valid Email");
            EmailInfo.removeClass("Valid");
            EmailInfo.addClass("error"); 
            return false;

        }        
    }
</script>


<div> 
    <label for ="name">Full Name </label>
    <input id = "fname" name = "fname" type = "text"/> 
    <span id = "fnameInfo" > Whats your full name?</span>
</div>

在这里我创建一个表单,每次我点击提交,表单只留空白全名框不显示错误,其他框都没问题。

我希望错误显示在框中变为红色并在提交时留空。

1 个答案:

答案 0 :(得分:0)

从这个改变开始 - 你在两个测试中缺少():

form.on("submit",function(e) {   
  var OK = validateFName() && validateEmail() && validateTele() && validateEmail();         
  if (!OK) {
    e.preventDefault();
  }     
});