<form action="" method="post">
<div align="center"><legend>Add a Code</legend>
<label for="code"></label>
<input type="text" name="code" id="code" maxlength="10" />
<input type='button'
onclick=
"isAlphanumeric(document.getElementById('code'),'Your Submission Contained Invalid Characters');
isBadPhrase(document.getElementById('code'), 'Please Enter A Correct Friend Code!');"
value='Check Field' />
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isBadPhrase(elem,helperMsg){
var badPhrase=/EPW|ESW|\s/;
if (elem.value.match(badPhrase)){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
What is wrong here?
You aren't returning anything from your handler. You need to return a value (true/false) from the handler, especially if you want to stop the default. Note -- I'd also change the name of the "BadPhrase" method to "GoodPhrase" so that it matches the sense of the return value.
script:
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
function isGoodPhrase(elem,helperMsg){
var badPhrase=/EPW|ESW|\s/;
if (elem.value.match(badPhrase)){
alert(helperMsg);
elem.focus();
return false;
} else {
return true;
}
}
function checkInput(id) {
return isAlphanumeric(document.getElementById(id),'Your Submission Contained Invalid Characters')
&& isGoodPhrase(document.getElementById(id), 'Please Enter A Correct Friend Code!');
}
html:
<input type='button' onclick="return checkInput('code');" value='Check Field' />
EDIT:
If you do the validation on form submit it will run regardless of how the form is submitted. You can add it as a onsubmit handler in the form tag, like you did for the click handler of the button. The button should probably be a submit button if it is supposed to trigger form submission.
Note: my preference would be to add the handlers via javascript rather than in the tag, but that's outside the scope of the question. I'd also probably use a framework rather than raw javascript, but that's also outside the scope.
Related
I'm fairly new to html/php/js and I'm running into an issue when conditionally submitting my form. Basically, what Im trying to do is have it where the confirm('Do you want to submit this form?') function only shows up if every field has a value entered (the checkform() function). If both are true, then the form will submit. Any help would be greatly appreciated, thanks!
<script type="text/javascript">
function checkform()
{
var myForm=document.frmhot;
if(myForm.status.value==""){
alert("Please select a timeframe status.");
return false;
myForm.status.focus();
}
if (myForm.line.value==""){
alert("Please select a line.");
return false;
}
if(myForm.reason.value==""){
alert("Please select a reason code.");
return false;
}
if(myForm.partnum.value==""){
alert("Please enter a part number.");
return false;
}
if(myForm.badgescan.value==""){
alert("Please enter a badge number.");
return false;
}
return true;
}
</script>
<form method="post" action="newhotpartgenerate.php" name="frmhot"
onclick="if(checkform();){
confirm('Do you want to submit the form?');
}
>
<input class="button_text" type="submit" value="Submit" name="submit" onclick= "checkform();" />
</form>
Complete working solution with corrections and tweaks for IE compatibility to a certain extend.
<script>
function checkform(evt) {
var myForm = document.frmhot;
var condition = true;
if(myForm.status.value==""){
alert("Please select a timeframe status.");
myForm.status.focus();
condition = false;
}
if (myForm.line.value==""){
alert("Please select a line.");
condition = false;
}
if(myForm.reason.value==""){
alert("Please select a reason code.");
condition = false;
}
if(myForm.partnum.value==""){
alert("Please enter a part number.");
condition = false;
}
if(myForm.badgescan.value==""){
alert("Please enter a badge number.");
condition = false;
}
if(condition){ condition = confirm('Do you want to submit the form?'); }
if(!condition) {
if(evt.preventDefault) { event.preventDefault(); }
else if(evt.returnValue) { evt.returnValue = false; }
else { return false; }
}
}
</script>
<form method="post" action="newhotpartgenerate.php" name="frmhot" onsubmit="checkform(event)">
<input type="text" name="status"/>
<input type="text" name="line"/>
<input type="text" name="reason"/>
<input type="text" name="partnum"/>
<input type="text" name="badgescan"/>
<input class="button_text" type="submit" value="Submit"/>
</form>
You have the right idea, just extract your code into its own function and then call that in the onclick.
Add this function:
function checkAndConfirm() {
if(checkform()) {
if (confirm('Do you want to submit the form?')) {
// submit the form
}
}
And then call it from the onclick attribute:
<form method="post" action="newhotpartgenerate.php" name="frmhot" onclick="checkAndConfirm()">
<button type="button" onclick="submitForm()">Submit</button>
When I press this button it runs a javascript validation function that returns true or false based on whether some data is formatted properly.
What I need to do next is: if true submit the validated data to mySql database using a php script.
I am stumped at how I can accomplish this. I hope I am clear. Thanks.
Also, I can't use ajax.
In the php file you can do all the mysql verifications needed.
The submit can be something like this
<form action="update.php" method="post"> <button type="submit" onclick="return submitForm()">Submit</button> </form>
Notice the return in the function call.
The verification is returning false when validation fails.
function submitForm() {
if(validation) { // fails
alert("your message");
return false;
}
}
Do your button type to submit and send to the form ex like this
<form action="update.php" method="post">
<button type="submit" onclick="submitForm()">Submit</button>
</form>
In index.php file check the mysql validation
You have missed the return in the function call. Try with
<button type="button" onclick="return submitForm()">Submit</button>
where you are returning false when validation fails.
function submitForm() {
if(validation) // fails
{
alert("your message");
return false;
}
}
use type = "submit" instead of button. try with -
<button type="submit" onclick="submitForm()">Submit</button>
js validation
function submitForm() {
//your validation codes
//if validates
return true
//else
return false;
}
if validation succeeds the the form will be submitted else will not be submitted.
HTML:
<button type="button" onclick="submitForm()">Submit</button>
JS:
function submitForm() {
if(){ //condition to validate
return true;
}else{
return false;
}
}
Also (as a suggestion) you can add a specific function to validate each type of value so then just call it in your function submitForm() by those types
You have missed the return in the function call. Try with
<button type="button" onclick="return submitForm()">Submit</button>
^
where you are returning false when validation fails.
function submitForm() {
if(validation) // fails
{
alert("your message");
return false;
}
}
Do your button type to submit and send to the form
ex like this
<form action="index.php" method="post">
....
<button type="submit" onclick="submitForm()">Submit</button>
</form>
In index.php file check the mysql validation
Hope this will help you
You need to add more detail from your html page. For instance the html form itself.
However just a hunch of what you are looking for.... you can use the folling command in your submitForm() function:
document.getElementById("myForm").submit();
We can't much help if we don't see your code. But in a nutshell you would submit the form by
document.getElementById('formId').submit();
What I need to do next is:
1->perform form.submit()
2->send all data's to database from your action file (action="action.php")
document.getElementById("form").submit()
<script type='text/javascript'>
function formValidator(){
// Make quick references to our fields
var firstname = document.getElementById('firstname');
var addr = document.getElementById('addr');
var zip = document.getElementById('zip');
var state = document.getElementById('state');
var username = document.getElementById('username');
var email = document.getElementById('email');
// Check each input in the order that it appears in the form!
if(isAlphabet(firstname, "Please enter only letters for your name")){
if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){
if(isNumeric(zip, "Please enter a valid zip code")){
if(madeSelection(state, "Please Choose a State")){
if(lengthRestriction(username, 6, 8)){
if(emailValidator(email, "Please enter a valid email address")){
return true;
}
}
}
}
}
}
return false;
}
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function lengthRestriction(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}
function madeSelection(elem, helperMsg){
if(elem.value == "Please Choose"){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
</script>
<form onsubmit='return formValidator()' >
First Name: <input type='text' id='firstname' /><br />
Address: <input type='text' id='addr' /><br />
Zip Code: <input type='text' id='zip' /><br />
State: <select id='state'>
<option>Please Choose</option>
<option>AL</option>
<option>CA</option>
<option>TX</option>
<option>WI</option>
</select><br />
Username(6-8 characters): <input type='text' id='username' /><br />
Email: <input type='text' id='email' /><br />
<input type='submit' value='Check Form' />
</form>
I have a submit button that redirects to another page if all the required fields are filled out.
<input type="submit" onclick="validateForm();redirect();" class="someClass" value="Submit" />
Right now when the button is clicked, it calls both functions. How do I get it to where it does not call redirect if validateForm returns false?
Here is the validateForm function if it helps:
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}
}
<input type="submit" onclick="validateForm(); return false;" class="someClass" value="Submit" />
Change the input to the code above. Also change your function to reflect the code below.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}else {
redirect();
}
}
Add a onclick handler, say validateAndRedirect:
function validateAndRedirect()
{
if(validateForm())
{
redirect();
}
else
{
return false;
}
}
Add this to the button:
<input...onclick="validateAndRedirect()" ... >
This function will call validate(). If validation fails, will return false. This false will prevent the submit action of the button. If validation passes, it will call redirect.
Make the first function call the next one and add this to your HTML :
<input> type=button onclick="validateForm(); return false;" </input>
Putting 'return false' will prevent redirection and will give time for your function to execute.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
} else
redirect();
}
Additionally, I'd recommend to abstain from putting any code in your HTML. It is considered a "bad practice". However, if you still want to put your code, it'll be more appropriate to put it in the form as an "onsubmit" action:
<form onsubmit="validateForm()">
If you want the function to execute when the submit button is clicked, you can just add an event listener in your script and an id to your button, like this:
var button = document.getElementById("submit");
button.onclick = function validateForm() { /*same code as above..*/ };
Hope it helps!
I have a form and I am trying to run some validation on it to catch required fields on older browsers and Safari(!). The solution I have so far seems to almost work... When I submit the form with empty fields on Safari the error pops up, and then the form is submitted anyway. What am I doing wrong?
My form looks like this:
<form id="primaryPostForm" method="POST" >
<input type="text" name="iName" id="iID" maxlength="25" required="required" value="" />
<textarea class="tipContent requiredAttr" name="taName" id="taID" maxlength="150" required="required" ></textarea>
<input type="hidden" name="submitted" id="submitted" value="true" />
<input id="submitBtn" type="submit" value="Submit">
My validation looks like this:
function validate(){
$('#primaryPostForm').submit(function(){
$("#primaryPostForm .requiredAttr").each(function(){
if($(this).val().length < 1){
alert("Please make sure the fields are filled in - thanks");
return false;}
})//end each
})//end submit
}
The return false only exits from the each loop. You need to store a result that you can return from the function:
function validate(){
$('#primaryPostForm').submit(function(){
var result = true;
$("#primaryPostForm .requiredAttr").each(function(){
if($(this).val().length < 1){
alert("Please make sure the fields are filled in - thanks");
result = false;
return false; // exit loop
}
})//end each
return result;
})//end submit
}
First off, use e.preventDefault(); instead of return false.
To answer your question:
return false must be in the scope of the submit event callback:
function validate(){
$('#primaryPostForm').submit(function(e){
var ret = true;
$("#primaryPostForm .requiredAttr").each(function(){
if($(this).val().length < 1){
alert("Please make sure the fields are filled in - thanks");
ret = false;
}
});
if(!ret){
e.preventDefault();
}
});
}
A more concise and direct way to do this would be:
$('#primaryPostForm').submit(function(e){
var required = $(".requiredAttr", this).filter(function(){
return !this.value;
});
if(required.length){
alert("Please make sure the fields are filled in - thanks");
e.preventDefault();
}
});
Try this, refer to MDN
function validate(){
$('#primaryPostForm').submit(function(){
var result = [];
$("#primaryPostForm .requiredAttr").each(function(){
if($(this).val().length < 1){
result.push(false);
}
})//end each
result.some(function(element){return (element!=false)})
alert("Please make sure the fields are filled in - thanks");
})//end submit
}
I'm trying to validate my values for alphabets and numberic as well as checking from database. I have created a function of validation and declaring my onclick button with validation function.
Function:
<script>
function validate()
{
var StudentID= document.getElementById('StudentID').value;
var StudentName = document.getElementById('StudentName').value;
var StudentAdd = document.getElementById('StudentAdd').value;
if(StudentID.length ==0 || StudentName.length ==0)
{
alert("Please do not leave any blanks");
return false;
}
else
{
if(isNumeric(StudentID))
{ alert("correct") }
else { alert("Numbers only!"); return false;}
alert("Correct correct");
}
return true;
}
</script>
Sample Form:
<form id="Student" name="Student" method="post" action="nextpage.php">
<input name="StudentID" type="text" id="StudentID" value="<?php echo $StudentID?>"/>
<input name="StudentName" type="text" id="StudentName" value="<?php echo $StudentName?>"/>
<input name="StudentAdd" type="text" id="StudentAdd" value="<?php echo $StudentAdd?>"/>
<input type="submit" name="submit" value="Submit" onclick="return validate();"/>
</form>
I have already declared return validate function instead of calling my nextpage.php. But nothing popup for any alert. Kindly advise.
Thanks
Try including your scripts after the body tag to make sure it only references elements after it has already been loaded. Then put return true inside the else statement.
function validate()
{
var StudentID= document.getElementById('StudentID').value;
var StudentName = document.getElementById('StudentName').value;
var StudentAdd = document.getElementById('StudentAdd').value;
if(StudentID.length ==0 || StudentName.length ==0)
{
alert("Please do not leave any blanks");
return false;
}
else
{
if(isNumeric(StudentID))
{ alert("correct") }
else { alert("Numbers only!"); return false;}
alert("Correct correct");
return true;
}
}
Instead of the submit button's onclick, move the function to the form's onsubmit, like:
<form onsubmit="validate()" ...>
For the part of the 'if' statement that returns true you may run into some issues with the alerts() as the browser will be trying to submit the form, but over all it should work.
There is no isNumeric() function in JavaScript (I get Uncaught ReferenceError: isNumeric is not defined). You have to create it on your own: Validate decimal numbers in JavaScript - IsNumeric()