php validation: no spaces in string

I’m setting up a custom php form validation used in conjunction with wordpress contact form 7 plugin, I’ve set up a validation rule as the text field, I only want people to type 1 word (i.e. no spaces) and for that one word to begin with the letter s.
The letter s validation works just fine but while this works, the no spaces (one word) validation doesn’t seem to be working?
php:

if($name == 'FirstField') {
        $FirstField = $_POST['FirstField'];

        if($FirstField != '') {
            if (!preg_match("/(^[^s]|s)/i",$FirstField)){
                $result['valid'] = true;
            } else {
                $result['valid'] = false;
                $result['reason'][$name] = 'Invalid Entry.';
            }
        }
    }

Any suggestions would be greatly appreciated!

Related posts

Leave a Reply

3 comments

  1. Test:

    if($name == ‘FirstField’) {
    $FirstField = $_POST[‘FirstField’];

        if($FirstField != '') {
            if (!preg_match("/(^[^s]|+s)/i",$FirstField)){
                $result['valid'] = true;
            } else {
                $result['valid'] = false;
                $result['reason'][$name] = 'Invalid Entry.';
            }
        }
    }
    

    UPDATED:

    if($name == 'FirstField') { $FirstField = $_POST['FirstField'];
    
        if($FirstField != '' && isset($FirstField) ) {
            $FirstField = explode(' ', $FirstField); //Get only first word
            if (!preg_match("/(^[^s]|+s)/i",$FirstField[0])){
                $result['valid'] = true;
            } else {
                $result['valid'] = false;
                $result['reason'][$name] = 'Invalid Entry.';
            }
        }
    }
    

    FIXED ERROR last:

    replace:

    if($FirstField != ” && isset($FirstField)

    by:

    if($FirstField != ” && isset($FirstField) )

    I hope help you.

  2. Starting with ‘s’ (case insensitive), no spaces: preg_match('/^s[^ ]*$/i', $string)

    Starting with ‘s’ (case insensitive), no white-space (spaces, tabs, etc): preg_match('/^sS*$/i', $string)

    edit

    You might also be interested in w, which matches “word characters” (A-Z, a-z, 0-9, _): preg_match('/^sw*$/i', $string)