简体   繁体   中英

Php form validation, Post

Here is my header for my form.

<form action="/page" id="landing_form" method="post" style="top:<?php echo get_post_meta($p->ID, 'top', true); ?>px; left:<?php echo get_post_meta($p->ID, 'left', true); ?>px;"  >

And a simple text field within my form, and submit button

<label>Email</label><input type="text" value="" id="landing_email" name="email" >
<input type="submit" name="submit" value="<?php echo get_post_meta($p->ID, 'button', true); ?>" class="landing_submit" id="landing_submit">

Now how would I make a function that checks if the email has a "."/"@" in it? Or is a specific string.

I have tried in my header to put something like onSubmit="return function('email);" and then putting the function within the file.

However it doesn't even check the function, and just submits the form regardless.

Assuming you want client-side validation you will have to create a javascript function like in this post

Therefore you will need your method:

<script>
function validateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
} 
function validate(email) {
    if (!validateEmail(email)) {
        return false;
    }

}
</script>

Then on the form you insert:

onSubmit="validate(email);"

This should not allow the form submission if the email is not valid. Please be aware that you will have to validate the email on the server side also.

the "onSubmit" attribute calls a piece of javascript when the submit button is pressed. It doesn't interact with your PHP at all.

What you'll probably want in your "page" page is something like the following:

<?php 
    if(isset($_POST['submit']))
    {
        $email = $_POST['email'];
        if(strpos($email, '@') && strpos($email, '.') && strpos($email, 'some specific string'))
        {
            // This code executes
            // only if there is an @
            // and a full stop and "some specific string"
            // inside the email
        }
    }
?>

Strpos is a function that searches for a substring within a string and returns the position of its first occurrence. If it cannot find the substring, it returns false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM