Home > Software design >  Checking fields
Checking fields

Time:10-15

I am just learning php, I have an email protection function

php.blade

@php

$split = explode('@', $email);
$first = $split[0];
$second = $split[1];

@endphp
<a href="" data-first="{{ $first }}" data-second="{{ $second }}" class="js-combaine-email"></a>

js

$(function () {
    $('.js-combaine-email').each(function () {
    var mail = $(this).data('first')   '@'   $(this).data('second');

    $(this).text(mail);
    $(this).on('click', function() {
      document.location.href = 'mailto:'   mail;
    });
    })
})

I need to make a check in php in case email is empty or the value does not contain @

Will it be something like this?

$message = '';

if (empty('@') && empty($email)) {
    $message .= "All values ​​are empty";    
}
else {
    if (empty('@')) {
        $message .= "No value @";    
    } 
    if (empty($email)) {
        $message .= "Email field is empty";    
    }
}

How to apply all this to work correctly?

CodePudding user response:

If the variable $email contains the actual email, then you can use the PHP function named filter_var to check if $email is in a valid email format :

if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Invalid email format";
}

https://www.php.net/manual/fr/function.filter-var.php

CodePudding user response:

You can use filter_var method to sanitize and validate the email format.

The script will look like this.

$email  = $_POST['email'];
$sanitizeEmail = filter_var($email, FILTER_SANITIZE_EMAIL);

if (filter_var($sanitizeEmail, FILTER_VALIDATE_EMAIL) === false || $sanitizeEmail!= $email) {
    echo "This email adress isn't valid!";
    exit(0);
}
  • Related