Validating form using jQuery.click does not work - javascript

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.

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>

JS - See which "or" evaluated true in if statement

I have the following JS (with jQuery):
if ($('#username').val() === '' || $('#password').val() === '') {
return;
}
$.ajax(); //run an ajax call to the server for password verif (this would have proper ajax code).
What this means is: if the username (#username) or password (#password) field are blank, then return.
I want to give the user a message if this is the case. Something like:
if ($('#username').val() === '' || $('#password').val() === '') {
if ($('#username').val() === '' && $('#password').val() !== '') {
alert('Please enter a username');
return;
}
if ($('#username').val() !== '' && $('#password').val() === '') {
alert('Please enter a password');
return;
}
alert('Username and password fields cannot be blank');
}
However, that is a lot of code. I am looking for something like an XOR/^ operator (from SQL), but for JS. Or something which says, "Good! The first expression was true and the second one was false - he didn't enter in a username but entered in a password. Let's tell him to enter in a username. Or - he didn't enter in a password? Tell him to enter in a password. And finally - he didn't enter in anything? Well tell him to enter in a username and password.
I am aware that the current code I have would do that, but I am looking for a simpler, more DRY conformant code.
My research on google has not come up with any solutions, and thus I am asking stackoverflow.
Thank you.
If you only want to use if statements, you can simplify the code to
var usernameMissing = $('#username').val() === '';
var passwordMissing = $('#password').val() === '';
if (usernameMissing || passwordMissing) {
if (usernameMissing && !passwordMissing) {
alert('Please enter a username');
} else if (!usernameMissing && passwordMissing) {
alert('Please enter a password');
} else {
alert('Username and password fields cannot be blank');
}
return;
}
or
var usernameMissing = $('#username').val() === '';
var passwordMissing = $('#password').val() === '';
if (usernameMissing && !passwordMissing) {
alert('Please enter a username');
return;
}
if (!usernameMissing && passwordMissing) {
alert('Please enter a password');
return;
}
if (usernameMissing || passwordMissing) {
alert('Username and password fields cannot be blank');
return;
}
However, to really cut down on the code you would use an array:
var missing = [];
if ($('#username').val() === '') {
missing.push("username");
}
if ($('#password').val() === '') {
missing.push("password");
}
if (missing.length > 0) {
alert("Please enter "+missing.join(" and ")+"!");
return;
}
which you can further generalise with a loop if you have more fields.
You can simply do empty check by this way. It is precise to check with a trim for whitespace also.
if (!$('#username').val()) {
alert('Please enter a username');
return;
}
if (!$('#password').val()) {
alert('Please enter a password');
return;
}
Simply loop your required fields and add message to data attribute. This can be used for any number of fields without changing JS code.
$(document).ready(function() {
$(document).on('submit', 'form', function() {
var valid = true;
$('label.required').css({
'border-color': 'grey'
}).find('.error').remove();
$('label.required').each(function() {
if (!$(this).find('input').val().length) {
valid = false;
$(this)
.css({
border: '1px solid red'
})
.append('<div class="error">' + $(this).data('msg') + '</div>');
}
});
return valid;
})
});
label {
border: 1px solid grey;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label class='required' data-msg="You must enter username">
Username:
<input type="text" id="username" />
</label>
<label class='required' data-msg="Password can not be empty">
Password:
<input type="password" id="password" />
</label>
<button>Login</button>
</form>
You can use else if(...) statements, something like:
if ($('#username').val() === '' && $('#password').val() === '') {
alert('Username and password fields cannot be blank');
}else if($('#username').val() === ''){
alert('Please enter a username');
}else if($('#password').val() === ''){
alert('Please enter a password');
}else{
// All Good.
}
Why so many conditions? You could do it like this:
if ($('#username').val() === '') {
alert('Please enter a username');
return;
} else if ($('#password').val() === '') {
alert('Please enter a password');
return;
}

ELSE IF Statement not validating information

Validate form has been working fine but I have now tried adding email validation to the code and now nothing will validate, form submits without any popup error boxes.
Here's The Current Code:
<script type="text/javascript">
function validateForm(){
var a=document.forms["order_form"]["fname"].value;
var b=document.forms["order_form"]["address"].value;
var c=document.forms["order_form"]["city"].value;
var d=document.forms["order_form"]["pcode"].value;
var e=document.forms["order_form"]["email"].value;
var atpos=email.indexOf("#").value;
var dotpos=email.lastIndexOf(".").value;
if (a==null || a=="")
{
alert("Full name must be filled out");
return false;
}
else if (b==null || b=="")
{
alert("Address must be filled out");
return false;
}
else if (c==null || c=="")
{
alert("City must be filled out");
return false;
}
else if (d==null || d=="")
{
alert("Post-Code must be filled out");
return false;
}
else if (e==null || e=="")
{
alert("Email Address must be filled out");
return false;
}
else if (atpos<1||dotpos<atpos+2||dotpos+2>=email.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
Form is likely submitting due to the following errors
Change:
var atpos=email.indexOf("#").value;
var dotpos=email.lastIndexOf(".").value;
To
var atpos=e.indexOf("#");
var dotpos=e.lastIndexOf(".");
indexOf() returns a number not an object so there is no value property.
Also as noticed by #fpierrat email should be e
I don't see any declaration for email before following:
var atpos=email.indexOf("#").value;
var dotpos=email.lastIndexOf(".").value;
Maybe you meant e, not email?
Also delete the .value after indexof() calls, see #charlieftl's answer, we were quite complementary on this ;-)

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;
}

Input validation with regex

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)) { ... }

Categories