JavaScript program to check if the variable is a valid string variable

This JavaScript program can be used to validate the string, to check whether value of a variable is a string or not?
Submitted by Abhishek Pathak, on June 14, 2017

Strings are arguably the most important data type in JavaScript. Whether you fetch a value from a form or seek a user input, most of the time it is encoded as string.

Here is a program that checks if any variable is a valid string. By the term valid we mean that:

  1. It is a string type variable
  2. It is not undefined
  3. Its value is not null

JavaScript code to validate string

    var myString = "Hello";
    if(((typeof myString != "undefined") && (typeof myString.valueOf() == "string")) && (myString.length > 0)) {
        console.log("String variable");
    else {
        console.log("Not a String variable!");

We define a myString variable which we will be testing.

Firstly, we check if the variable is not undefined. We test these conditions in if statement. Using the typeof variable we get the data type of the variable. If it is not undefined, along with its data type as string type and its value is not null.

The valueOf method returns the value of the variable. We are testing the value with the typeOf operator to check if it is a string.

Lastly, we simply check if the string is not null by applying length method and check if it is greater than 0. If the length is greater than 0, then of course, it is not empty.

Finally, we console.log out the print statement.

Here is the output of JavaScript:

string validation in JavaScript (JS)

JavaScript Examples »



Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.