3

Should I use is_email() to validate an email field? In WP. I've put the email field in a widget. I would really appreciate some help.

function update($new_instance, $old_instance) {
     $instance = $old_instance;
     $instance['email'] = is_email($new_instance['email']);

    return $instance;
     }

And

<p>
    <label for="<?php echo  $this->get_field_id('email'); ?>">
     <?php _e('Email'); ?>  </label>
     <input class="widefat" id="<?php echo $this->get_field_id('email'); ?>" name="<?php echo $this->get_field_name('email'); ?>" type="email" value="<?php echo $email; ?> " />
    </p>
    <?php
    }

Is using is_email() correct for this? Thank-you!

1 Answer 1

2

According to the documentation, is_email() is used to validate an email and either returns the email if it is valid or false if it isn't. So are using it correctly.

The only thing I can see in your code is that if the email is not valid, you are settings the data to a boolean value of FALSE.

 $instance['email'] = is_email($new_instance['email']);
 //with a bad email address, this will be the same as writing
 $instance['email'] = false;

Depending on what you're doing in the widget that may give you unexpected results.

I would instead do something like the following

$instance['email'] = ( is_email($new_instance['email']) ) ? $new_instance['email'] : '';

This is going to make sure that if the is_email() call returns false then you are setting $instance['email'] to an empty string instead of a boolean value.

Hope this helps!

2
  • Thank-you. In my widget, $instance['email'] = ( is_email($new_instance['email']) ) ? $new_instance['email'] : ''; goes in the update function. Should I use $email = esc_attr($instance['email']); in the form function? I would really appreciate it if you could answer this too. Thank-you
    – user28566
    Aug 11, 2014 at 18:24
  • 1
    typically if something is going into a form it's best to use esc_attr(). That's what it's there for :)
    – Welcher
    Aug 11, 2014 at 19:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.