我使用 Wordpress 为网站创建了自定义联系表单。
发送表格时所有字段均为必填项。如果出现错误,验证将在 Javascript 中完成,以避免重新加载页面。所有验证字段都可以正常工作,除了复选框之外。
我猜问题出在 javascript 中,我试图检查复选框是否已被选中。
创建表单的 PHP 函数:
<?php
add_shortcode( 'contact-form', 'site_contact_form' );
function site_contact_form() {
$validation_messages = [];
$success_message = '';
if ( isset( $_POST['contact_form'] ) ) {
//Sanitize the data
$firstname = isset( $_POST['firstname'] ) ? sanitize_text_field( $_POST['firstname'] ) : '';
$surname = isset( $_POST['surname'] ) ? sanitize_text_field( $_POST['surname'] ) : '';
$email = isset( $_POST['email'] ) ? sanitize_text_field( $_POST['email'] ) : '';
$phone = isset( $_POST['phone'] ) ? sanitize_text_field( $_POST['phone'] ) : '';
$acceptance = isset( $_POST['acceptance'] ) ? sanitize_text_field( $_POST['acceptance'] ) : '';
//Validate the data
if ( strlen( $firstname ) === 0 ) {
$validation_messages[] = esc_html__( 'Por favor introduzca un nombre.', 'sobrado' );
}
if ( strlen( $surname ) === 0 ) {
$validation_messages[] = esc_html__( 'Por favor introduzca un apellido.', 'sobrado' );
}
if ( strlen( $email ) === 0 or
! is_email( $email ) ) {
$validation_messages[] = esc_html__( 'Por favor introduzca un email válido.', 'sobrado' );
}
if ( strlen( $phone ) === 0 ) {
$validation_messages[] = esc_html__( 'Por favor introduzca un teléfono.', 'sobrado' );
}
if ( strlen( $acceptance ) === 0 ) {
$validation_messages[] = esc_html__( 'Por favor marca la casilla.', 'sobrado' );
}
//Send an email to the WordPress administrator if there are no validation errors
if ( empty( $validation_messages ) ) {
//$mail = get_option( 'admin_email' );
$to = '[email protected]';
$subject = 'Nuevo mensaje de ' . $firstname .' '. $surname;
$message = 'El email del cliente es: ' . $email;
wp_mail( $to, $subject, $message );
$success_message = esc_html__( 'Su mensaje ha sido enviado con éxito.', 'sobrado' );
}
}
//Display the validation errors
if ( ! empty( $validation_messages ) ) {
foreach ( $validation_messages as $validation_message ) {
echo '<div class="c-form__validation-message">' . esc_html( $validation_message ) . '</div>';
}
}
//Display the success message
if ( strlen( $success_message ) > 0 ) {
echo '<div class="c-form__success-message">' . esc_html( $success_message ) . '</div>';
}
?>
<div id="validation-messages-container" class="c-form__validation"></div>
<form id="contact-form" class="c-form__form" action="<?php echo esc_url( get_permalink() ); ?>" method="post">
<input type="hidden" name="contact_form">
<div class="c-form__section c-form__section--firstname">
<label for="firstname" class="c-form__label"><?php echo esc_html( 'Nombre', 'sobrado' ); ?></label>
<input type="text" id="firstname" class="c-form__input" name="firstname" placeholder="<?php echo esc_html( 'Nombre', 'site' ); ?>">
</div>
<div class="c-form__section c-form__section--surname">
<label for="surname" class="c-form__label"><?php echo esc_html( 'Apellidos', 'sobrado' ); ?></label>
<input type="text" id="surname" class="c-form__input" name="surname" placeholder="<?php echo esc_html( 'Apellidos', 'site' ); ?>">
</div>
<div class="c-form__section c-form__section--phone">
<label for="phone" class="c-form__label"><?php echo esc_html( 'Telefóno', 'sobrado' ); ?></label>
<input type="text" id="phone" class="c-form__input" name="phone" placeholder="<?php echo esc_html( 'Telefóno', 'site' ); ?>">
</div>
<div class="c-form__section c-form__section--email">
<label for="email" class="c-form__label"><?php echo esc_html( 'Email', 'sobrado' ); ?></label>
<input type="email" id="email" class="c-form__input" name="email" placeholder="<?php echo esc_html( 'Email', 'site' ); ?>">
</div>
<div class="c-form__section c-form__section--footer">
<div class="c-form__section c-form__section--acceptance">
<input type="checkbox" id="acceptance" class="c-form__checkbox" name="acceptance" value="Yes">
<label for="acceptance" class="c-form__label c-form__label--acceptance"><?php echo esc_html( 'Al confirmar mis datos acepto la política de privacidad y términos y condiciones.', 'site' ); ?></label>
</div>
<input type="submit" id="contact-form-submit" class="c-form__submit" value="<?php echo esc_attr( 'Enviar', 'site' ); ?>">
</div>
</form>
<?php
}
?>
JS:
const contactFormSubmit = document.getElementById('contact-form-submit');
if(contactFormSubmit){
contactFormSubmit.addEventListener('click', validateForm);
function validateForm(event) {
event.preventDefault();
event.stopPropagation();
// Name
const firstname = document.getElementById('firstname') !== null ?
document.getElementById('firstname').value :
'';
// Surname
const surname = document.getElementById('surname') !== null ?
document.getElementById('surname').value :
'';
// Phone
const phone = document.getElementById('phone') !== null ?
document.getElementById('phone').value :
'';
// Email
const email = document.getElementById('email') !== null ?
document.getElementById('email').value :
''; '';
// Checkbox
const acceptance = document.getElementById('acceptance') !== false ?
document.getElementById('acceptance').value :
'';
const validationMessages = [];
if (firstname.length === 0) {
validationMessages.push('Por favor introduzca un nombre.');
}
if (surname.length === 0) {
validationMessages.push('Por favor introduzca un apellido.');
}
if (phone.length === 0) {
validationMessages.push('Por favor introduzca un teléfono.');
}
if (email.length === 0 || !emailIsValid(email)) {
validationMessages.push('Por favor introduzca un email válido.');
}
if (acceptance.checked == false) {
validationMessages.push('Por favor marca la casilla.');
}
if (validationMessages.length === 0) {
//Submit the form
document.getElementById('contact-form').submit();
} else {
//Delete all the existing validation messages from the DOM
const parent = document.getElementById('validation-messages-container');
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
//Add the new validation messages to the DOM
validationMessages.forEach(function(validationMessage, index) {
//add message to the DOM
const divElement = document.createElement('div');
divElement.classList.add('validation-message');
const node = document.createTextNode(validationMessage);
divElement.appendChild(node);
const element = document.getElementById('validation-messages-container');
element.appendChild(divElement);
});
}
}
/**
* A simple function that verify the email with a regular expression.
*
* @param email
* @returns {boolean}
*/
function emailIsValid(email) {
const regex = /\S+@\S+\.\S+/;
return regex.test(email);
}
}
谢谢你。
在@mykaf和@Barmar的帮助下,我重写了复选框的JS代码。现在可以完美运行了。
const acceptance = document.getElementById('acceptance').checked ? document.getElementById('acceptance').value : '';
if (acceptance.length === 0) {
validationMessages.push('Some text');
}