Input validation with regex - javascript

I am trying to validate the PHP page input with regular expression but I am totally new here and need some assistance
<script>
function addplaces()
{
valid=true;
placename=document.getElementById("placename").value;
city=document.getElementById("city").value;
province=document.getElementById("province").value;
country=document.getElementById("country").value;
category=document.getElementById("category").value;
placepicture=document.getElementById("placepicture").value;
descp=document.getElementById("descp").value;
if(placename=="" || preg_match("^[A-Z]'?[- a-zA-Z]( [a-zA-Z])*$", placename))
{
alert("Please Enter Place Name");
document.getElementById("placename").focus();
valid=false;
}
else if(city=="")
{
alert("Please Enter City Name");
document.getElementById("city").focus();
valid=false;
}
else if(province=="")
{
alert("Please Enter province Name");
document.getElementById("province").focus();
valid=false;
}
else if(country=="")
{
alert("Please Enter country Name");
document.getElementById("country").focus();
valid=false;
}
else if(category=="")
{
alert("Please Enter category Name");
document.getElementById("category").focus();
valid=false;
}
else if(placepicture=="")
{
alert("Please Enter place picture");
document.getElementById("placepicture").focus();
valid=false;
}
else if(descp=="")
{
alert("Please Enter Description");
document.getElementById("descp").focus();
valid=false;
}
return valid;
}
</script>
I try to use preg_match(); but it does not work, please let me know where I am making a mistake.

preg_match is for PHP, that's why it doesn't work in your javascript code.
instead of preg_match("^[A-Z]'?[- a-zA-Z]( [a-zA-Z])*$" (you missed a ) here if you would programming in PHP)
use
var regex = new Regex( /^[A-Z]'?[- a-zA-Z]( [a-zA-Z])*$ );
if(regex.test(placename)) { ... }

Related

Returning false from onsubmit function doesn't prevent form from submitting

After I submit the form, the form will ignore the onsubmit whether the return is true or false, the form will directly go to form action.
I want to validate the input, if it is null it will remain on the same page and pop up an alert.
This is my JavaScript
<script>
function validLogin() {
if (document.login.username.value == "") {
alert("Please enter Login Name.");
document.loginform.userName.focus();
return false;
}
if (document.login.password.value == "") {
alert("Please enter password.");
document.userform.password.focus();
return false;
}
alert("Welcome User");
return true;
}
</script>
This is my form
<form action="Login" method="post" name="login" onsubmit="return validLogin();">
The userName field is miscased in the code
<script>
function validLogin() {
if (document.login.username.value == "") {
alert("Please enter Login Name.");
document.login.username.focus();//Here
return false;
}
if (document.login.password.value == "") {
alert("Please enter password.");
document.login.password.focus();
return false;
}
alert("Welcome User");
return true;
}
</script>

I am trying to use use this validation in my html tag by using onsubmit=return validateForm()

//this is the javascript program for validation
function validateForm()
{
var name=document.myform.uname.value;
var password=document.myform.password.value;
var conpass = document.myform.repassword.value;
boolean valid = true;
if(password != conpass)
{
alert("password is not same");
valid=false;
}
else if(name==null || name=="")
{
alert("User Name should not be blank..");
valid=false;
}
else if(password==""|| password==null)
{
alert("Password should not be blank");
valid=false;
}
else if(!this.form.checkbox.checked)
{
alert('You must agree to the terms first.');
return false;
}
else{
return valid;
}
};
//and this is the html in which I am using this but it is not working properly,it is not taking the js validation and directly forwarding me to the reg.jsp page.
<form action="reg.jsp" name="myform" method="post" onsubmit="return validateForm()" >
In order to prevent submit via javascript, you have to return false in your onsubmit handler.
So the in the following line the validateForm() must return false:
<form action="reg.jsp" name="myform" method="post" onsubmit="return validateForm()" >
You have many if-else blocks that set the var valid = false and this is ok.
But this valid variable should be returned. You do this only in the last else blocks.
else if(!this.form.checkbox.checked)
{
alert('You must agree to the terms first.');
return false;
}
else{
return valid;
}
The previous checks are just preparing the variable, but don't return it.
And this is what you need to do.
Here is an example how it can be done:
function validateForm() {
var name=document.myform.uname.value;
var password=document.myform.password.value;
var conpass = document.myform.repassword.value;
var valid = true;
var message = "everything is valid";
if(password != conpass)
{
message = "password is not same";
valid = false;
}
else if(name==null || name=="")
{
message = "User Name should not be blank..";
valid = false;
}
else if(password==""|| password==null)
{
message = "Password should not be blank";
valid = false;
}
else if(!this.form.checkbox.checked)
{
message = "You must agree to the terms first.";
valid = false;
}
alert(message);
return valid;
};
Other improvement could be:
Reordering the conditions by descending importance.
For example: if the Term are not accepted, is not important, if the password is empty.
If password is empty, it is not important, if the conpass is the same.
Using html5, which hast more input types and adjustable build-in validation for common cases. See more here: http://html5doctor.com/html5-forms-input-types/

JavaScript not giving alert on invalid Confirm Password text

For proper registration, user is required to enter password two times and password in both these textboxes should match.
However, on validating this using this code, JavaScript is not showing alert dialog.
Here pswrd and pswrd1 are two textboxes of password type.
var message="";
var result=false;
if(pswrd.value!== pswrd1.value)
{
message+="\nPasswords did not match";
result=false;
}
if(!result)
{
alert(message);
}
Try this
var message="";
var result=false;
if(pswrd.value!== pswrd1.value)
{
message = "Passwords did not match";
result=false;
}
else {
result = true;
}
if(!result)
{
alert(message);
}
Try this code.
if(pswrd.value!== pswrd1.value)
{
alert("Password does not matched!");
return false;
}
Hope this help :)
if(pswrd.value !== pswrd1.value)
the text in bold above should be != and not !==
!== is not an operator, use == for equality and != for unequality

PHP Validation and Javascript Validation won't work together

When I combine my php form validation code with my javascript validation code, the javascript code fails to work when I hit the submit button. It will only validate the first form field and not the 3 others and then php will validate all fields. I don't want the php form validation to do anything until javascript has completed the form validation.
When I use only php or only javascript to validate, then the code works correctly. What am I missing here? Is it something to do with the beginning of the form?
"form name="contactform" id="contactform" method="post"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"
onsubmit="return validateentry();">"
Am I supposed to do the php form validation while "action" goes to a different web page?
The javascript code:
function validateemail()
{
var emailentry=document.forms.contactform.email.value;
at=emailentry.indexOf("#");
period=emailentry.lastIndexOf(".");
if(at < 1 || ( period - at < 2 ))
{
alert("Please enter correct email in the format of 'yourmail#yourwebsite.com'")
document.forms.contactform.email.focus();
return false;
}
return(true);
}
function validatephonenumber()
{
var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/;
var numbers = document.forms.contactform.phone.value;
var verified = re.exec(numbers);
if (!verified)
{
alert("Please enter a phone number in the format of 999-999-9999");
return false;
}
return(true);
}
function validateentry()
{
if(document.forms.contactform.name.value=="")
{
alert("Please provide your name.");
document.forms.contactform.name.focus();
return false;
}
if(document.forms.contactform.company.value=="")
{
alert("Please provide your company name. If you don't have one, simply state
that you don't.");
document.forms.contactform.company.focus();
return false;
}
if(document.forms.contactform.email.value == "")
{
alert("Please provide an Email address.");
document.forms.contactform.email.focus();
return false;
}else{
var validformat=validateemail();
if(validformat==false)
{
return false;
}}
if(document.forms.contactform.phone.value=="")
{
alert("Please provide a phone number in the format 999-999-9999.");
document.forms.contactform.phone.focus();
return false;
}
else if(document.forms.contactform.phone.value.length < 12)
{
alert("Please provide the phone number in the format of 999-999-9999.");
document.forms.contactform.phone.focus();
return false;
}
else
{
var validnumber=validatephonenumber();
if(validnumber==false)
{
return false;
}}
if(document.forms.contactform.msg.value=="")
{
alert("Please provide a message.");
document.forms.contactform.msg.focus();
return false;
}
return(true);
}
It's unclear without more code but based on your comment I am going to guess that you have incorrectly written your php and it's breaking your javascript/html code. Perhaps one of your quotes? Look at the source code of the page and run it through one of the online validation services such as http://validator.w3.org and http://www.jslint.com
Try this:
PHP HTML:
<?php
echo "<form name='contactform' id='contactform' method='post'
action='' onsubmit='return validateentry(this);'>"
...
Validation JavaScript:
function validateemail(e)
{
var emailentry = e.value
, at = emailentry.indexOf("#")
, period = emailentry.lastIndexOf(".");
if(at < 1 || ( period - at < 2 ))
{
alert("Please enter correct email in the format of 'yourmail#yourwebsite.com'")
e.focus();
return false;
}
return true;
}
function validatephonenumber(e)
{
var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/
, numbers = e.value;
if (!re.exec(numbers))
{
alert("Please enter a phone number in the format of 999-999-9999");
e.focus();
return false;
}
return true;
}
function validateentry(f)
{
if(f.name.value == "")
{
alert("Please provide your name.");
f.name.focus();
return false;
}
if(f.company.value == "")
{
alert("Please provide your company name. If you don't have one, simply state
that you don't.");
f.company.focus();
return false;
}
if(f.email.value == "")
{
alert("Please provide an Email address.");
f.email.focus();
return false;
}
else
{
var validformat = validateemail(f.email);
if(validformat == false)
{
return false;
}
}
if(f.phone.value == "" || f.phone.value.length < 12 || (validnumber = validatephonenumber(f.phone)) == false)
{
alert("Please provide the phone number in the format of 999-999-9999.");
f.phone.focus();
return false;
}
if(f.msg.value == "")
{
alert("Please provide a message.");
f.msg.focus();
return false;
}
return true;
}

Validating form using jQuery.click does not work

Here is my code:
$('input#price_match_submit').click(function(event) {
if ($.trim($('input#price_match_competitor_price').val()) == '') {
alert("Please enter competitor's price.");
return false;
}
if ($.trim($('input#price_match_name').val()) == '') {
alert("Please enter your name.");
return false;
}
if ($.trim($('input#price_match_quantity').val()) == '') {
alert("Please enter the quantity.");
return false;
}
if ($.trim($('input#price_match_email').val()) == '') {
alert("Please enter your email address.");
return false;
}
if ($.trim($('input#price_match_competitor_website').val()) == '') {
alert("Please enter competitor's website.");
return false;
}
if ($.trim($('input#price_match_phone_number').val()) == '') {
alert("Please enter your phone number.");
return false;
}
});
Here #price_match_submit is a submit button. When I click on the button, this function should execute and validate the form. But it's not working as I am expecting. The form is being submitted without any validation. Where I am doing wrong?
You might instead want to hook into the submit event of the parent form and need to prevent the default behaviour:
$('#form').on('submit', function (e) {
if (everything_failed) {
e.preventDefault();
return false;
}
});
return false; only stops event bubbling I think.
You can validate like this
$('form').on('submit', function() {
// do validation here
if ($.trim($('input#price_match_competitor_price').val()) == '') {
alert("Please enter competitor's price.");
return false;
}
if ($.trim($('input#price_match_name').val()) == '') {
alert("Please enter your name.");
return false;
}
if ($.trim($('input#price_match_quantity').val()) == '') {
alert("Please enter the quantity.");
return false;
}
if ($.trim($('input#price_match_email').val()) == '') {
alert("Please enter your email address.");
return false;
}
if ($.trim($('input#price_match_competitor_website').val()) == '') {
alert("Please enter competitor's website.");
return false;
}
if ($.trim($('input#price_match_phone_number').val()) == '') {
alert("Please enter your phone number.");
return false;
}
});
return false if not validated.
$(#price_match_submit').click(function(event) {
if ($.trim($('input#price_match_competitor_price').val()) == '') {
alert("Please enter competitor's price.");
event.preventDefault();
}
else if ($.trim($('input#price_match_name').val()) == '') {
alert("Please enter your name.");
event.preventDefault();
}
else if ($.trim($('input#price_match_quantity').val()) == '') {
alert("Please enter the quantity.");
event.preventDefault();
}
else if ($.trim($('input#price_match_email').val()) == '') {
alert("Please enter your email address.");
event.preventDefault();
}
else if ($.trim($('input#price_match_competitor_website').val()) == '') {
alert("Please enter competitor's website.");
event.preventDefault();
}
else if ($.trim($('input#price_match_phone_number').val()) == '') {
alert("Please enter your phone number.");
event.preventDefault();
}
// if nothing happened until now, the form will be submited
});
Thank you for all your answer and comment.
This code works fine. There was some issue with other parts of code.
When we assign a function to an element, the function is assigned to that physical element only. But when we do some physical modification to the elements, all its previous properties get lost. In my code, I was displaying this html in a modal popup. Which was copying the html instead of using the same elements. So, it lost this binding with the function. And this is the reason this code was not working.

Categories