I'm trying to validate an input before I include another PHP so the user can get the error on the same page if there's one.. 4 inputs are required but the others are optional.. what I want to do is if the user only fill in the 4 required inputs validate the inputs than include another PHP file (instead of including the PHP I put a JavaScript instead to alert me that the code functions well..) and if the user also fill in the other optional inputs to also validate them and include a PHP file the problem I'm having is that it still alert me the code is good even when the user inserts invalid characters.
I only want it to process the last JavaScript if the user fills in the inputs with the allowed characters..
Here's the PHP:
<?php
// define variables and set to empty values
$titleErr = $MdescripErr = $posterErr = $vcodeErr = $vcode2Err = $vcode3Err = $mlink1Err = $mlink2Err = $mlink3Err = "";
$title = $Mdescrip = $poster = $comment = $vcode = $vcode2 = $vcode3 = $mlink1 = $comment = $mlink2 = $mlink3 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["title"]))
{$titleErr = "title is required";}
else
{
$title = test_input($_POST["title"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[A-Za-z0-9 ]*$/",$title))
{
$titleErr = "Only letters and white space allowed";
}
}
if (empty($_POST["Mdescrip"]))
{$MdescripErr = "Movie Description is required";}
else
{
$Mdescrip = test_input($_POST["Mdescrip"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[A-Za-z0-9 ]*$/",$Mdescrip))
{
$MdescripErr = "Only letters and white space allowed";
}
}
if (empty($_POST["poster"]))
{$posterErr = "Poster Link is required";}
else
{
$poster = test_input($_POST["poster"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$poster))
{
$posterErr = "Invalid URL";
}
}
if (empty($_POST["vcode"]))
{$vcodeErr = "Embed Link is required";}
else
{
$vcode = test_input($_POST["vcode"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$vcode))
{
$vcodeErr = "Invalid URL";
}
}
if (empty($_POST["vcode2"]))
{$vcode2 = "";}
else
{
$vcode2 = test_input($_POST["vcode2"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$vcode2))
{
$vcode2Err = "Invalid URL";
}
}
if (empty($_POST["vcode3"]))
{$vcode3 = "";}
else
{
$vcode3 = test_input($_POST["vcode3"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$vcode3))
{
$vcode3Err = "Invalid URL";
}
}
if (empty($_POST["mlink1"]))
{$mlink1 = "";}
else
{
$mlink1 = test_input($_POST["mlink1"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$mlink1))
{
$mlink1Err = "Invalid URL";
}
}
if (empty($_POST["mlink2"]))
{$mlink2 = "";}
else
{
$mlink2= test_input($_POST["mlink2"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$mlink2))
{
$mlink2Err = "Invalid URL";
}
}
if (empty($_POST["mlink3"]))
{$mlink3 = "";}
else
{
$mlink3 = test_input($_POST["mlink3"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$mlink3))
{
$mlink3Err = "Invalid URL";
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($title == NULL || $Mdescrip == NULL || $poster == NULL || $vcode == NULL)
{
}
else if (!preg_match("/^[A-Za-z0-9 ]*$/",$title) ||!preg_match("/^[A-Za-z0-9 ]*$/",$Mdescrip) || !preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$poster) || !preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$vcode))
{
}
else
{
?>
<script>
alert("it went through");
</script>
<?php
}
?>
You should try to split the url and remove the unnecesary items like "https://" so you can take one url like "http://www.stackoverflow.com/bla/bla/bla" and split it into ["http","","www.stackoverflow.com","bla","bla","bla"]
And finally check if each element is set(valid), this will make your validation quite simple
Related
Requirement : To validate password and emailID entered by user.
I have designed a dialog for user to enter there email id and password for creating their new account.
I want the the user input to be validated on the "next" button of the dialog.
I have written a JavaScript for it as shown below and added a custom action in "do action" of my dialog button.
function validatePassword(str szPasswordportal)
{
var newPassword = szPasswordportal;
var minNumberofChars = 6;
var maxNumberofChars = 20;
var regularExpression = /^[A-Za-z0-9`~!#%]{6,20}$/;
alert(newPassword);
if(newPassword = "") //if null
return false;
if(newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars)
{
return false;
}
if(!regularExpression.password(newPassword))
{
alert("password should contain atleast one number ,one alphabet and one special character");
return false;
}
return true;
}
But this JS is not getting executed successfully.
Can someone help me out with this or with some other suggestion?
Your if condition have a syntax mistake.
if(newPassword = "")
= is assigning operator. If you want to check the value you have to use conditional operator == like below.
if(newPassword == "")
Also you have to add all the condition on else part, then only it will check the validation one by one, otherwise at the end it will automatically return the true value. Change your script like below.
function validatePassword(str szPasswordportal)
{
var newPassword = szPasswordportal;
var minNumberofChars = 6;
var maxNumberofChars = 20;
var regularExpression = /^[A-Za-z0-9`~!#%]{6,20}$/;
alert(newPassword);
if(newPassword == "" || newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars)
{
return false;
} else if(!regularExpression.password(newPassword))
{
alert("password should contain atleast one number ,one alphabet and one special character");
return false;
} else {
return true;
}
}
I want to validate this text field email which contains Multiple emails; all separated by semi colons but this isn't working. It should break when msn.com have been entered along with other emails.
var isMsn = ["msn.com"];
function myFunction() {
var str = email.value;
//var isMsn = str.includes("msn.com");
var res = str.split(";");
var isValid = false;
//alert(res.length);
for (var i = 0; i < res.length; i++){
//alert(res[i]);
var x = res[i];
//check to see if this is an valid emAIL then
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(x.match(mailformat)){
alert("valid email address!");
//IF isMsn = TRUE then check to see if is contains msn.com
if (x.contains(isMsn) ){
alert("it is MSN");
//res[+1];
isValid = true;
}
else {
alert('no MSN');
if (res.includes(isMsn)){
//alert('Cannot mix MSN emails with other');
//isValid = false;
//res[-1];
break;
}
//else{
//alert('it is other');
//isValid = true;
//}
}
}
else{
alert("You have entered an invalid email address!");
isValid = false;
}
}
}
I want it to loop through and all the emails must either match a msn.com or other NOT Both. for example, user#msn.com;user1#msn.com or user#hotmail.com;user1#hotmail.com but NOT user#msn.com;user1#hotmail.com
Not sure if .includes is the best option or not!
1) You should use includes instead of contains;
2) The includes or contains method accepts a string, not an array, so it should be res.includes(isMsn[0]);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
And if you want to validate by multiple domains - you should not name it isMsn, but prohibitedDomains and then to Array.some (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) over this array.
prohibitedDomains.some((domain) => res.includes(domain))
I need help in email validation, this validation code all email in specific format like, test#test.gov.au, test#something.ac.au and i want it to be allowed in format test#something.au
(Note : Here I am only allowed to get entry for 5 domains that is gov.au, edu.au, govt.nz, ac.au and csiro.au)
My code is as follow
JS:
function emailTldValidation(tlds) {
$.validator.addMethod("emailTld", function(value,element) {
if (value.search("#") != -1) {
return (/(.+)#(.+)\.(gov\.au|edu\.au|ac\.nz|csiro\.au|govt\.nz)$/).test(value);
//return (/(.+)#(.+)\.(csiro\.au|gov|gov\.us)$/).test(value);
}
return false;
},"Please enter valid tld like "+tlds);
$.validator.addClassRules({
stringInput: {
emailTld: true
}
});
}
And the following code is validate in function.php
function validateEmail($email) {
//validate email here from server side
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//validate tld
$validTlds = str_replace(".", "\.", VALID_EMAIL_TLDS);
$validTlds = "\.".str_replace(",", "|\.", $validTlds);
$emailArr = explode("#", $email);
$emailTld = $emailArr[1];
if (preg_match('/^[-a-z0-9]+\.[a-z][a-z]|('.$validTlds.')\z/', strtolower($emailTld))) {
//check main domain here
$exValidTlds = explode(",", VALID_EMAIL_TLDS);
$exValidTlds = array_map('trim', $exValidTlds);
foreach($exValidTlds as $tld) {//if exist then
if(strstr($emailTld, ".".$tld)) {
if($tld == strrchr($emailTld, $tld)) {
return true;
}
}
}
return false;
}
}
function validateEmail($email) {
//validate email here from server side
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//validate tld
$validTlds = str_replace(".", "\.", VALID_EMAIL_TLDS);
$validTlds = "\.".str_replace(",", "|\.", $validTlds);
//$validTlds = str_replace(",", "|\.", $validTlds);
$emailArr = explode("#", $email);
$emailTld = $emailArr[1];
if ($emailTld == 'csiro.au')
{
//check main domain here
return true;
}
elseif (preg_match('/^[-a-z0-9]+('.$validTlds.')\z/', strtolower($emailTld))) {
//check main domain here
$exValidTlds = explode(",", VALID_EMAIL_TLDS);
$exValidTlds = array_map('trim', $exValidTlds);
foreach($exValidTlds as $tld) {//if exist then
if(strstr($emailTld, ".".$tld)) {
if($tld == strrchr($emailTld, $tld)) {
return true;
}
}
}
return false;
}
}
return false;
}
This regexp worked pretty well for me:
.+#(?:(?:govt*)|(?:edu)|(?:ac)|(?:csiro))\.(?:au|nz)
I used this tool to create it: http://regexpal.com/
FYI, validating email is incredibly difficult: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html
Edit: After re-reading your question, it seemed like you might need validation for emails with subdomains and such as well. This is probably better suited for more open ended domains:
.+#(?:\w+\.\w+)
Edit 2: So the problem is that your validation is too light for your complexity.
.+#(?:(?:.+\.(?:(?:govt*)|(?:edu)|(?:ac))\.(?:au|nz))|(?:csiro\.au))
Breaking it down:
.+ // Match at least 1 of any character
# // An # symbol
(?: // The group of everything right of the # symbol
(?: // The group of domains that have subdomains
.+\. // At least one character in front of a .
(?: // govt, edu or ac
\. // a dot
(?: // au or nz
(?: // or simply 'csiro.au'
You can't get around the fact that four of your domains need a subdomain, and one does not.
I am trying to validate a html form using a javascript function, but the function is never matching the values to regex even when they are correct. This is what I have:
function validateForms(form){
var usZipRegex = '^\d{5}[[$-.+ ]?\d{4}]?$|^\d{5}$';
var canZipRegex = '^[ABCEGHJKLMNPRSTVWXY][\d][ABCEGHJKLMNPRSTVWXYZ][\W]?[\d][ABCEGHJKLMNPRSTVWXYZ][\d]$';
var nameRegex = '^[A-Za-z][ -a-zA-Z]+$';
var emailRegex = '^[^\.#]([\w]*\.)*[^\.#]*#[a-zA-Z0-9-]{1,63}(\.[a-zA-Z0-9-]{1,63})+$';
var name = form.name.value;
var zip = form.zip.value;
var email = form.email.value;
var comment = form.comment.value
if(name == "") {
alert('You must enter your name.');
return false;
}
if(name != nameRegex) {
alert('You have entered an invalid name.');
return false;
}
if(email == "") {
alert('You must enter your email.');
return false;
}
if(email != emailRegex) {
alert('You have entered an invalid email.');
return false;
}
if(zip == "") {
alert('You must enter your zip code.');
return false;
}
if((zip != usZipRegex) & (zip != canZipRegex)) {
alert('You have entered an invalid zip code.');
return false;
}
if(comment == "") {
alert('You must enter a message.');
return false;
}
return true;
}
The (name != nameRegex) parts always return true, but should not. The (name == "") parts do work on their own though.
You're comparing the raw strings, not running the regex. name != nameRegex will always return true unless the person's name is literally ^[A-Za-z][ -a-zA-Z]+$. You need to set up nameRegex properly as a regex object, but in your code, it's just a string. You also need to use test or another one of the RegExp object's methods to check for a match, not the ==/!= operators. This is true for the other patterns as well.
Constructing a regex is done one of two ways:
var regex1 = /[a-z0-9]/;
var regex2 = new RegExp('[a-z0-9]');
If you do it like this, though, it's just a string:
var notARegex = '[a-z0-9]';
Your code should be closer to this style:
var nameRegex = /^[A-Za-z][-a-zA-Z ]+$/; //note that the hyphen has been moved
//...
if (!nameRegex.test(name)) {
alert('You have entered an invalid name.');
return false;
}
Edit: There's more going wrong here. Your other regex code could use some major improvements:
var usZipRegex = /^\d{5}([$.+ -]?\d{4})?$/;
var canZipRegex = /^(?![DFIOQU])[A-Y]\d(?![DFIOQU])[A-Z]\W?\d(?![DFIOQU])[A-Z]\d$/;
var nameRegex = /^[a-z][a-z\s-]+$/i;
var emailRegex = /^[^.#]+#[^.#]{1,63}(\.[^.#]{1,63})+$/i';
I don't know if your Canadian zip code pattern is correct, but the email one was definitely wrong (email is WAY more complicated than you think, so it's best to be very permissive with it).
For example, I want to test a postcode is valid so I test the postcode using my regular expressions in a 'if else' scenario and call the function when the form is submitted.
function validatePostal(postalCode)
var re = new RegExp(/^([a-zA-Z]{2})([0-9]{1,2})[ ]([0-9]{2})([a-zA-Z]{1,2})$/);
var re2 = new RegExp(/^([cC]{1})([aA]{1})(2|18|17)[ ]([0-9]{2})([a-zA-Z]{1,2})$/);
var str = shipPostalCode.value;
if (re.test(str))
{
return true;
}
else if (re2.test(str))
{
return true;
alert("Congratulations!!");
}
else
{
alert("That is not a valid postcode. Please verify your input. Format should be AA11 11AA");
return false;
}
}
onclick="return (validatePostal(postalCode)"
How would i go about testing said postcode against another regular expression and then if the postcode is valid, only displaying a message to those in a particular area.
e.g. those who entered CA4 would get a message and those who entered DA4 would not?
Okay, so assuming that both re and re2 are the regular expressions for postcodes you want to accept, you could have a structure like:
if (re.test(str) || re2.test(str))
{
return true;
}
else
{
alert("That is not a valid postcode. Please verify your input. Format should be AA11 11AA");
return false;
}
Now if you want to do another check, like you said about "DA4" versus "CA4", you would have another regular expression for that (lets call it re3 to be consistent), and you could then have an inner if statement, like so:
if (re.test(str) || re2.test(str))
{
if (re3.test(str)) {
alert("You entered a CA4 postcode!");
} else {
alert("You did not enter a CA4 postcode :(.");
}
return true;
}
else
{
alert("That is not a valid postcode. Please verify your input. Format should be AA11 11AA");
return false;
}
function validatePostal(postalCode)
var re = new RegExp(/^([a-zA-Z]{2})([0-9]{1,2})[ ]([0-9]{2})([a-zA-Z]{1,2})$/);
var re2 = new RegExp(/^([cC]{1})([aA]{1})(2|18|17)[ ]([0-9]{2})([a-zA-Z]{1,2})$/);
var str = shipPostalCode.value;
var isPostalCodeValid = false;
if (re.test(str))
{
isPostalCodeValid = true;
}
else if (re2.test(str))
{
alert("Congratulations!!");
isPostalCodeValid = true;
}
if(isPostalCodeValid){
//Check for Postalcode and show mssg or not
}else{
alert("That is not a valid postcode. Please verify your input. Format should be AA11 11AA");
return false;
}
}
onclick="return (validatePostal(postalCode)"