开发者

PHP Regex Problem (username, birthdate, email address)

开发者 https://www.devze.com 2023-01-08 08:47 出处:网络
The below regex\'s don\'t seem to be working. Is it because of !preg_match? Username if (!preg_match(\"/^[A-Za-z](?=[A-Za-z0-9_.]{3,31}$)[a-zA-Z0-9_]*\\.?[a-zA-Z0-9_]*$/\",$_POST[\'username\'])) {

The below regex's don't seem to be working. Is it because of !preg_match?

Username

if (!preg_match("/^[A-Za-z](?=[A-Za-z0-9_.]{3,31}$)[a-zA-Z0-9_]*\.?[a-zA-Z0-9_]*$/",$_POST['username'])) {
    $hasErr = true;
    $return['username'] = 'Please enter a valid username. Use 4 to 32 characters '
                        . 'and start with a letter. You may use letters, numbers, '
                        . 'underscores, and one dot (.).';
}

Birthdate

if (!preg_match("'\b(0?[1-9]|1[012开发者_运维知识库])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2}\b'", $_POST['birthdate'])) {
    $hasErr = true;
    $return['birthdate'] = 'Please enter your birthdate in a valid format. mm/dd/yyy';
}

Email Address

if (!preg_match("'\b[A-Z0-9._%-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b'",$_POST['email'])) {
    $hasErr = true;
    $return['email'] = 'Please enter a valid email address.';
}


Here's what I would do

<?php

// remove whitespaces
array_walk($_POST, 'trim');

function validate() {
    $return = array();
    if (!preg_match('/^[A-Za-z](?=[A-Za-z0-9_.]{3,31}$)[a-zA-Z0-9_]*\.?[a-zA-Z0-9_]*$/',$_POST['username'])) {
        $return['username'] = 'Please enter a valid username. Use 4 to 32 characters '
                            . 'and start with a letter. You may use letters, numbers, '
                            . 'underscores, and one dot (.).';
    }

    if (!preg_match('/^(0?[1-9]|1[012])[- .\/](0?[1-9]|[12][0-9]|3[01])[- .\/](19|20)?[0-9]{2}$/', $_POST['birthdate'])) {
        $return['birthdate'] = 'Please enter your birthdate in a valid format. mm/dd/yyy';
    }

    // email regexes are pretty problematic
    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $return['email'] = 'Please enter a valid email address.';
    }

    return (empty($return)) ? true : $return;
}

echo '<pre>';
var_dump(validate());
echo '</pre>';

?>

Note: I didn't check your username regex.

0

精彩评论

暂无评论...
验证码 换一张
取 消