I am trying to create an input field to input the amount. If the amount is less than 200 it will show the error message.
This is the code:
<?php
$paid_amount = sanitize_text_field( $_POST['paid_amount'] )
$match_amount = isset($paid_amount) ? $paid_amount : '';
$validate_amount = preg_match( '/[0-9]/', $match_amount );
if( !isset($paid_amount) || empty($paid_amount) )
wc_add_notice( esc_html__( 'The paid amount can not be empty.', 'mpdc'), 'error' );
if( !empty($paid_amount) && $validate_amount == false )
wc_add_notice( esc_html__( 'Minimum payment must be 200 or more.', 'mpdc'), 'error' );
?>
I am totally new. I searched everywhere but couldn't find any answer.
CodePudding user response:
The question is an example of a XY problem, since you shouldn't use regular expressions for this in the first place.
Looking at your question and your code, we can conclude that it tries to do this:
- Fetch the amount from the request
- If no amount was received, show message
- If amount less than 200, show message
Now we can translate that into code. If we try and make things as simple as possible, which is good practice, we can do this:
// Fetch the amount and cast it as an integer
$amount = (int)($_POST['paid_amount'] ?? 0);
// If no amount
if ($amount === 0)
wc_add_notice( esc_html__( 'The paid amount can not be empty.', 'mpdc'), 'error' );
// If amount less than 200
if ($amount < 200)
wc_add_notice( esc_html__( 'Minimum payment must be 200 or more.', 'mpdc'), 'error' );