How to highlight word containing not allwowed character in php
Below is code to find error in a sting $noticeText
function AddressOnlyValidatorNoticeTemp($str_fieldValue)
{
$str_pattern = '/[^A-Za-z0-9 #.,:()%?!^[#\]*{}\/&_-\\s]/'; // 25-08-2010
preg_match_all($str_pattern, $str_fieldValue,$matches);
if($matches[0] != null)
{
$message = "Only 'A-Z a-z 0-9 # . , ( ) & % ? [ ] # * { } _ / -' Characters Allowed";
}
else
{
$message = 1;
}
return $message;
}
if (!$errFlag)
{
$errMsg = AddressOnlyValidatorNoticeTemp($noticeText);
if ($errMsg != 1)
{
$errMsg = "Notice Details : ".$errMsg;
$errFlag = true;
}
}
My issue is how to highlight word containing character not allowed in $str_pattern.
Thanks
Related
I am trying to code a form for a login using php to check it. But I can't get it to check the if I have any whitespaces and special characters for the username. I tried using the [\W]+ but that did not work.
<?php
$usernerr = "";
$passwerr = "";
$usern = "";
$passw = "";
$pattern = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(empty($_POST['uname']))
{
$usernerr = "*Please add a username please!";
}
else
{
$usern = clearInput($_POST['uname']);
if(!preg_match('/s/', $usern) || !preg_match($pattern, $usern))
{
$usernerr = "*Username have only letters and numbers!";
}
$usernerr = "";
}
if(empty($_POST['psw']))
{
$passwerr = "*Please add a password please!";
}
else
{
$passw = clearInput($_POST['psw']);
$passwerr = "";
}
}
function clearInput($input)
{
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
}
?>
Considering the error message you wrote, you are complicating yourself.
Instead of searching for the list of characters that aren't alpha num, search for alpha num only. Try using this pattern, and don't negate the condition.
$pattern = "/^[a-zA-Z0-9]+$/";
// Some code...
if(preg_match($pattern, $usern))
// ^-------------------------------Notice the changes
{
//Username is valid
}
Description of the pattern :
^ from the begining
[a-zA-Z0-9] search an alpha num
+ 1 or more time
$ to the end
/^[a-zA-Z0-9]+$/can be replaced by /^[[:alnum:]]+$/ or /^[a-z\d]+$/i which produce the same effect.
Please see the following code. I want to remove all the unauthorized characters such as . / \ | !##$%^&*() _ - = + ~ < > , ? : ; " ' [] { } and the ` character and and all the empty spaces input.
I want receive only English characters and Numbers allowed.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = test_input($_POST["user"]);
$password = test_input($_POST["pass"]);}
How should be the test_input() function?
function test_input($string){
if(preg_match('/[^a-z_\-0-9]/i', $string))
{
echo "not valid string";
}
}
The following code validates a new user password by asking them to confirm their password by entering it twice:
// search to see if is a vvalid file path
if (($val["type"] == "password") && !strstr($key , "_confirm")) {
$name = $val["name"] ? $val["name"] : $key ;
if ($input[$name] != $input[$name . "_confirm"]) {
//preparing the message
$fields["error"] = "Password and confirmation doesn't match.";
$fields["errors"][$name] = 1;
$fields["errors"][$name . "_confirm"] = 1;
$fields["values"] = $input;
}
}
I would like to include additional validation (i.e., password contains at least 1 number and 1 letter, special characters [!##$%], must be at least 8 characters in length.
What would be the proper code syntax to nest with the above code? THX
To add the validation, you need to find the Regex you like, e.g.
http://regexlib.com/Search.aspx?k=password&AspxAutoDetectCookieSupport=1
Then use that regex in your code (replace $regEx with your choice):
if (($val["type"] == "password") && !strstr($key , "_confirm")) {
$name = $val["name"] ? $val["name"] : $key ;
if ($input[$name] != $input[$name . "_confirm"]) {
//preparing the message
$fields["error"] = "Password and confirmation doesn't match.";
$fields["errors"][$name] = 1;
$fields["errors"][$name . "_confirm"] = 1;
$fields["values"] = $input;
}
if( !preg_match( $regEx, $input[$name] ) ) {
$fields["error"] = "Password must contain...";
$fields["errors"][$name] = 1;
$fields["values"] = $input;
}
}
For one-upper, one-lower, and one-digit w/ min 8 chars:
$regEx = '/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/';
Add in some special-char requirements:
$regEx = '/^(?=.*[!##$%])(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/';
What would be the best way to code for the following
To check if its empty
That its alpha
Length
I am wanting a way that I am able to combine the following if statements
Current Code
if (isset($_POST['submitButton'])) {
$fullName = $_POST['fullname'];
if(fullName != ' ')
{
$errorfullName .= 'Please Enter Your Name';
}
}
}
if statements that need to be included:
if (!ctype_alpha(str_replace(array("'", "-"), "",$fullName))) {
$errorfullName .= '<span class="errorfullName">*First name should be alpha characters only.</span>';
}
if (strlen($fullName) < 3 OR strlen($fullName) > 40) {
$errorfullName .= '<span class="errorfullName">*First name should be within 3-40 characters long.</span>';
}
Your are missing $ sign before fullName.Use empty function to check weather the string is empty or not. Use the below code
if (isset($_POST['submitButton'])) {
$fullName = $_POST['fullname'];
if(empty($fullName))
{
$errorfullName .= 'Please Enter Your Name';
}
}
If you need to combine more statements, you can do it with ( if{} elseif{} else{/*NO ERROR*/}. But I think there is a smarter solution:
function valide_fulname($fullname) {
if (isset($fullName) && trim($fullName)!='')
return 'Please enter your name.';
if (!ctype_alpha(str_replace(["'", "-"], "", $fullName)))
return 'First name should be alpha characters only.';
if (strlen($fullName)<3 || strlen($fullName)>40)
return 'First name should be within 3-40 characters long.';
// no error
return false;
}
if (isset($_POST['submitButton'])) {
$error = valide_fullname($_POST['fullname']);
if (!$error)
echo "It's OK!";
else
echo '<span class="errorfullName">' . $error . '</span>';
}
I'm using the Contact Form 7 plugin on wordpress to collect data inputted in the fields, I'm now looking to set up some validation rules using this neat extension: http://code-tricks.com/contact-form-7-custom-validation-in-wordpress/
What I'm after is to only allow one word only in the text field (i.e. no whitespace) and this one word has to begin with the letter 'r' (not case sensitive).
I've written the no white space rule as follows:
//whitespace
if($name == 'WhiteSpace') {
$WhiteSpace = $_POST['WhiteSpace'];
if($WhiteSpace != '') {
if (!preg_match('/\s/',$WhiteSpace)){
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Invalid Entry.';
}
}
}
Is it possible to incorporate the second rule into this also? So no whitespace, and the word must begin with the letter 'r'? Any suggestions would be greatly appreciated!
EDIT:
seems core1024 answer does work, but only one of them:
//FirstField
if($name == 'FirstField') {
$FirstField = $_POST['FirstField'];
if($FirstField != '') {
if (!preg_match("/(^[^a]|\s)/i",$FirstField)){
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Invalid Entry.';
}
}
}
//__________________________________________________________________________________________________
//SecondField
if($name == 'SecondField') {
$SecondField = $_POST['SecondField'];
if($SecondField != '') {
if (!preg_match("/(^[^r]|\s)/i", $SecondField)) {
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Invalid Entry.';
}
}
}
I want to use this code twice, once to validate the first character being a on one field the second instance with the first character being r on another field. But it only seems the SecondField validation rule is working.
Try to use:
preg_match('/^r[^\s]*$/i',$WhiteSpace)
instead of:
!preg_match('/\s/',$WhiteSpace)
You need this:
if (!preg_match("/(^[^r]|\s)/i", $WhiteSpace)) {
It matches any string that doesn't start with r/R or contain space.
Here's a test:
$test = array(
'sad',
'rad',
'ra d'
);
foreach($test as $str) {
echo '"'.$str.'" -> '.preg_match('/(^[^r]|\s)/i', $str).'<br>';
}
And the result:
"sad" -> 1
"rad" -> 0
"ra d" -> 1