August 17, 201115 yr <?php $email = $_POST['email']; $regex = '/^([a-zA-Z0-9])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-]+)+/'; if (preg_match($regex, $email)) { echo $email . "is a valid email."; } else { echo $email . "is an invalid email."; } ?> <form action="try.php" method="post" /> Email<input type="text" name="email"> <input type="submit" name="submit" /> </form> http://bkwebdesignandhosting.co.uk/php/loginsystem/try.php I need to make it so the valid/invalid notice only appears after pressing submit, atm its always there, the code does work though
August 17, 201115 yr Just use an IF statement to check if $email has a value. On a side note I changed the regex to make it more effective validating an email, making sure that it is invalid when no domain is entered, e.g. it will now be invalid when they enter an email like "example@example" unlike before <?php $email = $_POST['email']; $regex = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$"; if(!empty($email)) { if (eregi($regex, $email)) { echo $email . " is a valid email."; } else { echo $email . " is an invalid email."; } } ?> <form action="try.php" method="post" /> Email<input type="text" name="email"> <input type="submit" name="submit" /> </form> Edited August 17, 201115 yr by Barth
August 17, 201115 yr Author thanks for cleaning up my regex code also could you please exsplain what this line does so i can apply it to other things if(!empty()
August 17, 201115 yr if(!empty($variable)) In human (Is the variable not empty?) It is basically checking if the variable contains something It can also be done in different ways, such as these if($variable!= null) if($variable!= "") Hope this helps
August 18, 201115 yr On a side note I changed the regex to make it more effective validating an email, making sure that it is invalid when no domain is entered, e.g. it will now be invalid when they enter an email like "example@example" unlike before The problem with this is that email addresses just like that will be perfectly valid soon enough, when ICANN allow any TLD from 2012 (provided someone will have the infrastructure to support the TLD)
August 18, 201115 yr As its PHP, I'd be tempted just to use filter_var() instead of Regex http://php.net/manual/en/filter.examples.validation.php
Create an account or sign in to comment