Form Validation Works But Does Not Prevent Form Submission - javascript

I use javascript to validate my form input and it works fine but the form still gets submitted when errors are not corrected.
How do I prevent form submission until the user makes corrections?
Sample Code Below;
$('.validate').hide();
$('body').on('blur', '#phone', function() {
$('.validate').hide();
isphone($(this).val());
});
function isphone(phone) {
if (phone === "1234" || phone === "23456") {
$(".validate").show();
} else {
$(".validate").hide();
}
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm">
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />
<div class="validate"><span style="color: red;"><b>Phone in use!</b></span></div>
<button href='/' type='submit' id="submitForm">Process</button>
</form>

To write a helpful answer, I made a small refactor, rewriting isphone to be a reusable validation function that just returns true or false. I renamed it too. Now we can reuse the validation logic in different places.
form elements emit a submit event just before they are actually submitted. We must listen for the sumbit event, and if validation fails, we can return false which will cancel the event, and therefore preventing form submission.
$('.validate').hide();
$('body').on('blur', '#phone', function() {
var value = $(this).val();
if (isPhoneInUse(value)) {
$(".validate").show();
} else {
$(".validate").hide();
}
});
$('#submitForm').on('submit', function(e) {
var value = $("#phone").val();
if (isPhoneInUse(value)) {
// validation failed. cancel the event
console.log("not submitting");
return false;
}
})
function isPhoneInUse(phone) {
return (phone === "1234" || phone === "23456")
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm">
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />
<div class="validate"><span style="color: red;"><b>Phone in use!</b></span></div>
<button href='/' type='submit' id="submitForm">Process</button>
</form>

Related

Which is the secure way to disable the button?

I have a form and enabling the submit button after fill the all the fields in the form. I used jquery to disable the button also use the disabled="disabled" in the submit button. Now I am on the browser and button is showing disabled.
Now What I did, Right clicked and inspect elements and goes to my register button and I remove the disabled=" disabled" from the HTML and my button got enable without filling the details and I clicked no button form submitted.
I just want to know Is there any other solution to handle this issue? because anyone can enable this and access it without filling the form.
Would you help me out in this?
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
<form>
Username<br />
<input type="text" id="user_input" name="username" /><br />
Password<br />
<input type="password" id="pass_input" name="password" /><br />
Email<br />
<input type="text" id="email" name="email" /><br />
<input type="submit" id="register" value="Register" disabled="disabled" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
The disabled property is good but its more or less cosmetics.
There is a simple way to prevent a form submit using JavaScript submit Event handler. You check for a condition to be met - otherwise you cancel the submission.
You can prevent form submit by simply modifying your function to this:
(function() {
$('form > input').keyup(function(e) {
e.preventDefault();
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()

Jquery: On form submit validate then allow default operation to continue

Wondering, is there a way to make a form execute default operation after preventingDefault and validating form fields.
$('#form').submit(function (e) {
e.preventDefault();
var isValid = true;
var name = $('#name').val();
if (empty(name)) {
isValid = false;
}
$(this).submit() // This will cause a stack overflow :)
});
After I complete the form validation I want to proceed as normal,
I thought of using onClick on the submit button, but users can trigger submit by hitting on the enter key, which I want to allow. Reason why I want to do this is so that the server can perform its operations like redirecting.
I am writing you a small example.
$(document).ready(function(){
$("#control_form").on("keyup", function(event){
post_control();
});
});
var post_control = function(){
var user_name = $("#user_name").val();
if ( user_name==null || user_name=="" || user_name.length < 4 )
$('.error').html("Username can not be less than 4 characters!");
else
{
$('.error').empty();
$('#control_form').removeAttr('onsubmit');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id="users_form">
<form name="form" id="control_form" action="post_form" method="post" onsubmit="return false;">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name">
<input type="submit" value="Save">
</form>
<div class="error"></div>
</div>
Instead of using preventDefault, you can return true at the end of the function.
If you want to prevent the submission, you can return false.
Here's an example using your code. If you try to submit the form with an empty field, it won't submit. If you fill the field, it will:
$("#form").submit(function() {
var name = $("#name").val();
if (!name) {
$(".form-group").addClass("has-danger");
alert("Field is blank. Submit will be prevented.");
return false; // no submission
}
alert("Field is filled. The form will submit.");
return true; // form submits
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='form'>
<div class="form-group">
<label class="form-control-label" for="name">Name</label>
<input type="text" class="form-control" id="name">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
CodePen Demo
check this it works.I tested it.
$(document).ready(function(){
$('#form1').submit(function (e) {
if($('#name').val() == ''){
alert('Name is empty');
return false;
}
$(this).submit();
});
});

Submit a form if the statement is true

I am trying to write a very simple jQuery function which will have two main properties. The first one will be to check if the field is empty or not. The second one will be if the field is not empty to execute a form which will lead to a PHP coded page. I am very new to jQuery and I will be very grateful if someone can point where exactly is my mistake. Thank you in advance.
function Captcha() {
$('#Button').click(function() {
if ($("#Field").val().length == 0) {
alert("Please fill the box");
return false;
} else {
alert("Your code is saved");
return true;
}
});
}
$(document).ready(function() {
Captcha();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="success.php" id="Alpha" method="post" onsubmit="return Captcha();">
<input id="Field" type="text" placeholder="Enter key here">
<button id="Button" type="submit" form="Alpha">Confirm</button>
</form>
Don't work with the button's click event, work with the form's submit event because a form can be submitted via the keyboard and therefore the button can be circumvented.
You can see a working version here (Stack Overflow prevents submit code from working in the snippet environment below.)
$(function() {
$('#Alpha').on("submit", function() {
if ($("#Field").val().length == 0) {
alert("Please fill the box");
return false;
} else {
alert("Your code is saved");
return true;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="success.php" id="Alpha" method="post" onsubmit="return Captcha();">
<input id="Field" type="text" placeholder="Enter key here">
<button id="Button" type="submit" form="Alpha">Confirm</button>
</form>
You would want to validate the form fields when you actually submit the form. When you click on the button you are still in the process of triggering the submit.
Try changing this:
$('#Button').click(function() {
Into this:
$('#Alpha').on('submit', function() {
See if that helps.

What is wrong whit this jQuery submit function?

This code runs smoothly except submit function. If I change the submit function with another function such as "show();" it works. Why doesn't it run this submit function?
$(document).ready(function() {
$('#submit').click(function() {
var email = $('#email').val();
email = $.trim(email);
var password = $('#password').val();
password = $.trim(password);
if (email == "" || password == "") {
$('.division').show();
} else {
$('#form').submit();
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form" method="post" action="run.php">
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<input type="checkbox" checked="checked" id="keep" value="yes">
<label for="keep">Keep login</label>
<input type="submit" id="submit" value="Sign in" onClick="return false;">
</form>
The problem is that you've given your submit button the id "submit". Browsers add elements to the form object using the id, so the normal submit function of the form is being replaced with a reference to your submit button.
Change the name (and probably id) of the submit button to (say) submit-btn and it will work. Live Example
Separately from that, though, I wouldn't hook click on the submit button at all; I'd hook submit on the form element, since forms can be submitted in other ways (pressing Enter in certain form fields, for instance).
Example: Live Copy
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<script>
$(document).ready(function(){
$('#form').submit(function(e){
var email = $('#email').val();
email = $.trim(email);
var password = $('#password').val();
password = $.trim(password);
if( email == "" || password == "") {
$('.division').show();
e.preventDefault(); // Don't allow the form submission
}else{
$('#form').submit();
}
})
});
</script>
<!-- Using GET rather than POST, and no action
attribute, so that it posts back to the jsbin page -->
<form id="form" method="get">
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<input type="checkbox" checked="checked" id="keep" value="yes">
<label for="keep">Keep login</label>
<input type="submit" value="Sign in">
</form>
<div class="division" style="display: none">Please fill in an email and password</div>
</body>
</html>
In your input element, you have onClick="return false;"This onClick function is being given priority over the click handler that you defined in jQuery. If you remove the onClick portion of your input element, your jQuery code will run.
Aside, there is a problem with your submit code in that it never actually prevents the POST to the server. See my edit below:
if( email == "" || password == "") {
$('.division').show();
return false;
}else{
('#form').submit();
}
You must explicitly return false to prevent the form from submitting to the server. Alternatively, you can just remove the else clause altogether, due to the fact that if the function doesn't explicitly return false, it will complete and continue with the form submission.
Also note that for form submissions, it is typically better to use the onSubmit event as opposed to the onClick event, since forms can technically be submitted by hitting the 'enter' key as well as clicking the submit button. When onClick is used, the submission is not triggered via hitting the enter key.

JS validation false, form still submitting

I've got a JS problem. My validation seems to be working, checking that the user inputs a valid number which isn't zero, but the form is still submitting. I have seen this question asked many times but I can't find a solution that works for me. Any ideas would be great.
My Javascript
function checkNotZero()
{
var theNumber = document.getElementById("theNumber").value;
var str = /^\+?[1-9]\d*$/.test(theNumber);
if ( str == false ) {
alert('You have not entered a valid number');
return false;
} else {
document.getElementById('numberCheck').submit();
}
}
My HTML
<form action="/next.php" method="post" id="numberCheck">
<input type="text" id="theNumber" value="0">
<button id="submitButton" OnClick="checkNotZero();">Add to Basket</button>
</form>
Use an <input type="submit"> for the submit button.
Validate on the form's submit event rather than some onclick. Forms can get submitted in other ways than just clicking a button (for instance, pressing "enter", or procedurally through code).
Prefer .addEventListener to attributes for attaching events to elements. Use preventDefault() to prevent form submission.
Hi for the above requirement of 'validating form' java script validation should be done
when the form gets submitted. follow the below approach, form will not get submitted
until and unless the validation is correct.
<html>
<head>
<script type="text/javascript">
function checkNotZero()
{
var theNumber = document.getElementById("theNumber").value;
var str = /^\+?[1-9]\d*$/.test(theNumber);
if ( str == false ) {
alert('in');
alert('You have not entered a valid number');
return false;
} else {
document.getElementById('numberCheck').submit();
}
}
</script>
</head>
<body>
<form action="/next.php" method="post" id="numberCheck" onsubmit="return
checkNotZero()">
<input type="text" id="theNumber" value="0">
<button id="submitButton">Add to Basket</button>
</form>
</body>
</html>
the only change is <form action="/next.php" method="post" id="numberCheck"
onsubmit="return checkNotZero()">
do not use onclick event in submit button.

Categories