Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use javascript regex to check for "empty" form fields?

I am working on a php+javascript based project and have already made up a mockup page at : my website

I knew how to use javascript or php to check whether a particular field of form is "empty"or not, that is, whether it contains alphanumerical characters other than whitepsace characters(for instance, space, tab and newline).

However, my normal apporach no longer works since the jquery plugin that I am using now relies on regex to validate the fields.

If you go to the third tab(3. Fill up Shipping Info and Make Payment), you can enter something into the Firstname field and it does the check automatically. Fine. However, if you just simply put some space characters there and jump to the next field, well, it still feels okay for that, which is not correct since no one's first name is nothing!

The problem? At the back it has a regex like this :

"noSpecialCaracters":{
                    "regex":"/^[0-9a-zA-Z ]+$/",
                    "alertText":"* No special caracters allowed"},

This would not filter out empty characters.

I searched online and tried my best to make up another regex to match, I tried

"regex":"/^[^]+$/"

for matching non-empty characters, but that will not do...

Can anyone help me out? Many thanks in advance!

like image 996
Michael Mao Avatar asked Feb 12 '10 03:02

Michael Mao


People also ask

Does empty RegEx match everything?

An empty regular expression matches everything.

How to use RegEx function in JavaScript?

As mentioned above, you can either use RegExp() or regular expression literal to create a RegEx in JavaScript. const regex1 = /^ab/; const regex2 = new Regexp('/^ab/'); In JavaScript, you can use regular expressions with RegExp() methods: test() and exec() .

How to check if string contains only letters JavaScript?

Use the test() method to check if a string contains only letters, e.g. /^[a-zA-Z]+$/. test(str) . The test method will return true if the string contains only letters and false otherwise.


2 Answers

Try this for non-whitespace:

([^\s]*)

Example:

/([^\s])/.test("   A"); //TRUE
/([^\s])/.test("    "); //FALSE
like image 187
Nick Craver Avatar answered Oct 28 '22 01:10

Nick Craver


function anyChar(str){
    return /\S+/.test(str);
}

will return false if emty data

like image 35
anonymous Avatar answered Oct 28 '22 02:10

anonymous