Craft 3 validate new password in change password I'm trying to validate user's new password and confirm password in my custom plugin init().

Event::on(User::class, User::EVENT_BEFORE_SAVE, function(Event $event) {
    $formData = $_POST;
    $newPassword =  $formData['newPassword'];
    $confirmPassword =  $formData['confirmPassword'];

    if ($newPassword != $confirmPassword){
        Craft::$app-&gt;session-&gt;setError('Confirm password does not match new password');
    }
});


On the template:

{% set error = craft.app.session.getFlash('error') %}
{% if error|length &gt; 0 %}
    {{error}}
{% endif %}


The problem with this is, it displays the message "Confirm password does not match new password" on frontend but the password gets changed into newPassword value. Is there a way to stop processing any further after returning error?
I believe what you're looking for is this:

if ($newPassword != $confirmPassword){
    Craft::$app-&gt;session-&gt;setError('Confirm password does not match new password');
    $event-&gt;isValid = false;
}


Setting isValid to false will stop further processing of that element (the user in this case).