I recently switched a input form from a text to a textarea so that I could have multiple lines of text. The form is working fine except when I go to validate. If it is one line, there is no problem but when I enter text that wraps to the second line, i get an error from my form validator (only letters and numbers are allowed) here is my code:
private function validate_alnum($var, $min=0, $max=0, $required=false, $err="") {
if($required==false && strlen($this->source[$var]) == 0) {
return true;
}
if(isset($this->source[$var])){
if(strlen($this->source[$var]) < $min) {
$this->errors[$var] = $err . ' is too short. It has to be at least '.$min. ' character(s)';
} elseif(strlen($this->source[$var]) > $max) {
$this->errors[$var] = $err . " is too long. It can't be more than ".$max. " characters";
} elseif(!preg_match("/^[a-zA-Z0-9 -.:,]*$/", $this->source[$var])) {
$this->errors[$var] = $err . ' is invalid. Only letters and numbers are allowed';
}
}
}
Your regex doesn't allow new lines. Try:
^[-a-zA-Z0-9\s.:,]*$
also -
should be the first or last character if you want it to be literal, otherwise it makes a range.
The \s
here will allow for single spaces, new lines, and tabs. ( Additional reading on the \s
)
If you change the quantifier to +
you can be sure there is more than 1 character in the string, which would take out your default $min
requirement (the error message would be less specific though).