mindfreak
mindfreak

Reputation: 455

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

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:

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;
        }
} 

Upvotes: 0

Views: 2351

Answers (2)

Sidd
Sidd

Reputation: 1397

Your code is pretty messed up. E.g, isNaN is a function that takes a value as an argument, returning true if it is not fully representable as a number. ref. So

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

So, it's not really useful for your purpose since any string, as long as it has any non-number, non-decimal-point characters, will evaluate to "not a number".

You also don't to create separate functions for validating fname and lname - since the majority of the code is the same, you should try to capture as much common usage as possible in a single function.

I haven't looked at your jQuery code or CSS, but here is a straight up JS solution that works, let me know if you have questions:

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;

Here's a fiddle: http://jsfiddle.net/etsnpj8n/

Upvotes: 1

My thought to validate input text fields is to use inbuilt html attributes. You can do lots of validations either using Html form or native javascript code.

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

You can add lot of styling using pseduo-classes with css like :valid, :invalid and :required. Using Html5, you can have custom error messages at field level. Using Html5, you can consolidate all form field errors in display at form level.

Upvotes: 0

Related Questions