How to validate a First & Last Name without using jQuery plugin

时间:2015-05-04 19:27:34

标签: javascript jquery html

I am looking to validate the First Name and Last Name as per the Google sign-up page using jQuery. My code displays the error message once the Input box is left empty. However, how do I go about clearing the error message once the input box is filled up with some data ??

I need to do the following things:

  • If both input boxes are empty, only one error message should pop-up, probably the second input box error message.

  • If the second box is non-empty, the error-message should be of first input box.

Meanwhile, I have also pasted the equivalent Javascript code which performs the validation as good as its required.

Could some help me how to get the same reflected in jQuery ?

HTML code:

<div class="first_container">Name</div>
    <div id ="nameBlock">
       <input type="text" name="fname" placeholder="First" id="cust_fname"/>
       <input type="text" name="lname" placeholder="Last"  id="cust_lname"/>
    </div>

 <div id="name_error_msg"> 
    <span id="spanUsernameRequired" style="visibility: hidden; font-weight:bold; color: Red;"></span>
    <span id="spanLastnameRequired" style="visibility: hidden; font-weight:bold; color: Red;"></span>
 </div>

CSS code:

.first_container {
    padding: 3px;
    width: 150px;
    font-style: italic;
    font-weight: bold;
    color: #a77;}

#nameBlock {
    display: inline-block;}

#cust_fname {
    margin: 3px;
    padding: 5px;
    width: 170px;}

#cust_lname {
    margin: 5px;
    padding: 5px;
    width: 170px;}

#name_error_msg{
    margin: 5px;
    color: red;}

jQuery code:

  $(document).ready(function() {
      var cust_fname = $('#cust_fname').val();
      var cust_lname = $('#cust_lname').val();
      var name_regex = /^[A-Za-z]+$/;

        $("input").blur(function(){
            if(cust_fname.length==0){
                $(name_error_msg).text("First name can't be empty");
                $(this).css("border-color", "red");
                return false;}

        $("input").focus(function(){
         $(name_error_msg).text("");
            if(cust_fname.length > 0) { 
                 $(":focus").$(name_error_msg).html().css("border-color", "green"); }
        });
      })
 });

Javscript code:

    function fname_validate(){  

    var x = document.getElementById("cust_fname").value;
    var regex_char = /^[A-Za-z]+$/;


    if((x == "") || (x==null)){

        document.getElementById("spanUsernameRequired").innerHTML = "<b><i>You can't leave First Name empty</b></i>";
        document.getElementById("spanUsernameRequired").style.visibility = 'visible'; 
        return false;
        }

    else if(isNaN){
        document.getElementById("spanUsernameRequired").innerHTML = "<b><i>No numbers allowed</b></i>";} 


    if(x.match(regex_char)){
        document.getElementById("spanUsernameRequired").innerHTML = "";
        document.getElementById("spanUsernameRequired").style.visibility = 'hidden';

        if((document.getElementById("cust_lname").value == "") || (document.getElementById("cust_lname").value==null)){
            document.getElementById("spanLastnameRequired").style.visibility = 'visible';
        }

        return false;}
    }


    function lname_validate(){

    var x = document.getElementById("cust_lname").value;
    var regex_char  = /^[A-Za-z]+$/;

        if(x=="" || x==null){
            document.getElementById("spanLastnameRequired").innerHTML = "<b><i>You can't leave Last Name empty</b></i>"; 
            document.getElementById("spanLastnameRequired").style.visibility = 'visible';
            /*document.getElementById("spanUsernameRequired").style.borderColor = 'red';*/
            return false;}


        else if(isNaN){
        document.getElementById("spanLastnameRequired").innerHTML = "<b><i> No numbers allowed </b></i>";
        }

        if(x.match(regex_char)){
            document.getElementById("spanLastnameRequired").innerHTML = "";
            document.getElementById("spanLastnameRequired").style.visibility = 'hidden';
            if((document.getElementById("cust_fname").value == "") || (document.getElementById("cust_fname").value==null)){
                document.getElementById("spanUsernameRequired").style.visibility = 'visible';
            }

            return true;
        }
} 

2 个答案:

答案 0 :(得分:0)

我想验证输入文本字段是使用内置的html属性。您可以使用Html表单或本机JavaScript代码进行大量验证。

<input type="text" required id="firstName" pattern="[A-Z]{3}[0-9]{4}" />

您可以使用带有css的pseduo-classes添加大量样式:valid,:invalid和:required。 使用Html5,您可以在字段级别拥有自定义错误消息。 使用Html5,您可以合并表单级别的所有表单字段错误。

答案 1 :(得分:0)

你的代码非常混乱。例如,isNaN是一个将值作为参数的函数,如果它不能完全表示为数字,则返回true。 ref。所以

isNaN("32") //returns false
isNaN("42.42") // returns false
isNaN("Adam43 Smith") // returns true

所以,它对你的目的并没有用,因为任何字符串,只要它有任何非数字,非小数点字符,就会评估为“不是数字”。

您也不需要创建单独的函数来验证fnamelname - 因为大多数代码是相同的,您应该尝试在单个代码中捕获尽可能多的常用用法功能。

我没有看过你的jQuery代码或CSS,但这是一个直接的JS解决方案,如果你有问题请告诉我:

var fname = document.getElementById("cust_fname"),
    lname = document.getElementById("cust_lname"),
    msg = document.getElementById("name_error_msg");

function check(){
    var error = "";

    if(fname.value && lname.value){ // both fields are filled, let's validate

        //check if either value contains any numbers
        if(/[0-9]/.test(fname.value) || /[0-9]/.test(lname.value)) 
            error = "<b><i>No numbers allowed</b></i>";

        //check if either value contains any characters besides words and hyphens
        else if(!/^[A-z/-]+$/.test(fname.value) || (!/^[A-z/-]+$/.test(lname.test))) 
            error = "<b><i>No spaces or special characters allowed</b></i>";
    }
    else if(fname.value) // means lname is empty
        error = "<b><i>You can't leave Last Name empty</b></i>";
    else if(lname.value) // means fname is empty
        error = "<b><i>You can't leave First Name empty</b></i>";
    else //both are empty
        error = "<b><i>Please input your full name</b></i>";

    if(error) msg.innerHTML = error;
    else {
        msg.innerHTML = "";
        //process form
    }
}

fname.onchange = check;
lname.onchange = check;

这是一个小提琴:http://jsfiddle.net/etsnpj8n/