简体   繁体   中英

Code needed for validation of a text field “without” whitespaces included in PHP

This is the code for validation of a text field "with" whitespaces allowed :-

function validateFirstName($fname){

if(empty($fname)){
    $firstnameErr = "First name is required";
    return $firstnameErr;
} else if (!preg_match("/^[a-zA-Z ]*$/", $fname)){ // check if name only contains letters and whitespace.Performs a regular expression match
    $firstnameErr = "Only letters are allowed";
    return $firstnameErr;
} 
   return ''; 
}  

I wanted the other part of the else if code of the same function which throws an error if there are whitespaces

// using Jquery

  else if($.trim($fname).length==0){
        $firstnameErr = "Value required";     
   }

// pure javascript without jquery

  else if($fname.replace(/\s+/g,'').length ==0){
        $firstnameErr = "Value required";     
   }

// in php

  else if(strlen(trim($fname))==0){
        $firstnameErr = "Value required";     
   }

You can use either

 return $fname.indexOf(' ') >= 0;

Or you can use the test method, on a simple RegEx:

 return /\s/g.test($fname);

it depends by what you are interested in:

if you're searching for whitespace only, you could use strpos function:

if (strpos($fname, " ") !== false) // whitespaces were found!

if you need to check every whitespace char (so tabs included, and more than one whitespace) you have to use the regexp specifying \\s that will search for whitespaces:

if (preg_match("/\\s/", $fname)) // okay, there are whitespaces in string (tabs, double spaces, etc...)!

in these cases, when the condition is true, you can launch an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM