Javascript/PHP Validation - javascript

I'm trying to prevent the form being submitted if the validation fails, however its not working at the moment. The onclick method is used for hidden input, but its the onsubmit method that is failing. Any ideas?
<input type="submit" class="btn ccm-input-submit" id="register" name="register" value="Register" onsubmit="return validation(this)" onclick="copytextbox()"/>
<?php echo $form->hidden('rcID', $rcID); ?>
<script>
function copytextbox()
{
var textToCopy = document.getElementById('school').value;
var whereToCopy = document.getElementById('<?php echo $school ?>');
whereToCopy.value += textToCopy;
}
function validation(f)
{
var schoolText = document.getElementById('school').value;
if (schoolText == '') {
alert('Please Choose a value from the dropdown box.');
return false; // stop submission until textbox is not ''
} else {
f.submit();
return false;
}
}
</script>
Also, im attempting to see if that value is a member of an array, I tried using indexOf(schoolText) etc but this also failed, kind regards

Move your onsubmit="return validation(this)" attribute from the <input> tag to the <form> tag.
Test an array like this:
// global array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function findFruit(val) {
if(fruits.indexOf(val) == -1 {
alert('not found');
} else {
alert('Found!')
}
}
findFruit('Peach'); // not found

Related

How to check if the user input exist in an Array?

Is there a way to check if an user input from text box (for example) exists in an array that I created and imported from other JS files?
And can I link all that code to an HTML button?
In Python to do this I use "in":
if a in List:
print("That's In")
PS: I know that List in Python are a little different with Arrays in JavaScript.
From my platform's JavaScript documentation:
//Use:
if (in_array('a', ['a','b',4,'z'])) {console.log('item in array.');}
//Prerequisite functions:
function in_array(s,a)
{
var r = false;
if (is_array(a))
{
for (var i = 0; i<a.length; i++)
{
if (a[i]==s) {r = true;}
}
}
else {console.log('Error: object to in_array ('+a+') is not an array.');
}
return r;
}
function is_array(a)
{
return ((a.constructor.toString().indexOf('Array') > 0) ? true : false);
}
Thanks for all, i think that i resolved my problem with array.indexOf
There's my solution below
How can i close the post ?
<!DOCTYPE html>
<form id="form" onsubmit="return false;">
<input style="position:absolute" type="text" id="userInput" /> <br>
<input style="position:absolute;" type="submit" onclick="name();" /> <br>
<script type="text/javascript">
function name() {
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var input = document.getElementById("userInput").value;
//Check if a value exists in the data1 array
if(fruits.indexOf(input) !== -1){
document.write(input, " Value exists!");
document.write(" Press F5 to reload")
} else{
document.write(input, " Value does not exists!");
document.write(" Press F5 to reload");
}
}
</script>
</form>
</html>

function compare with variable in mysql

<?php $check=$ word[ 'Word'][ 'en_words']; ?>
<form id="" method="post" action="">
<label>
<span id="first"><?= $check; ?></span>
<span>EN:</span>
<input type="text" id="second" />
</label>
<input type="button" class="button" value="Check" onclick="validate()" />
<script>
function validate() {
var first = document.getElementById('first').value;
var second = document.getElementById('second').value;
if (second == first) {
alert('Ok!');
} else {
alert('No!');
}
}
</script>
Why this script doesn't work, could someone see?
I want compare variable with input to $check (mysql record).
You didn't told us what the expected result is.
Anyway, I see that you use a document.getElementById('first').value on a ''. This funcion only works with form elements.
You should use something like: document.getElementById('first').innerHTML. So, your code should look like:
....
<script>
function validate(){
var first = document.getElementById('first').innerHTML;
var second = document.getElementById('second').value;
if (second == first){
alert('Ok!');
}
else {
alert('No!');
}
}
</script>
Ensure that the $check variable is being printed. You may need to echo or print the variable:
<span id="first"><?php print $check; ?></span>
Also, the span element does not contain a value. Instead, try capturing the value with innerHTML:
var first = document.getElementById('first').value;
Since first is html tag so it will have innerHtml and second is input so it will have value
<script>
function validate(){
var first = document.getElementById('first').innerHTML;
var second = document.getElementById('second').value;
if (second == first){
alert('Ok!');
}
else {
alert('No!');
}
}
</script>
<button onclick="validate()">Click</button>

checking value for element causing error on onsubmit

I have a form which I am trying to check color of the element before the page submits. I am trying to validate the form using a function called by the from using 'onsubmit='. If I add 'document.getElementById(name).style.backgroundColor' in the code below, when I submit the page it will go directly to the next page without asking if I want to go onto the next page or letting the user know the form has errors. It looks like the form is successfully calling both validate() and check_form() functions, but with the background color check it seems to not complete the validate() function. I've tested it without the 'style.backgroundColor' and it works fine (gives notice to user). What am I doing wrong?
Thanks
Simplified example of the code used:
<!DOCTYPE html>
<html>
<body>
<form class="bulk" onsubmit="return validate(this)" action="next_page.php" method="GET">
<input type="checkbox" id="checkbox" name ="checkbox">
<input type="text" id="sample" name="sample" value="">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var checkbox_name = 'checkbox';
var sample = 'sample';
sample = document.getElementById(sample);
//if checkbox is checked, make sure all the required fields are there
$("#"+checkbox_name).change(function(){
if(document.getElementById(checkbox_name).checked){
sample.style.backgroundColor = "red";
}
});
});
function validate(from) {
var valid = 'true';
if(check_form() == 'false'){
valid = 'false';
}
if(valid == 'false'){
alert('ERROR: Some inputs are invalid. Please check fields');
return false;
}
else{
return confirm('Are you sure you want to submit?');
}
}
function check_form(){
sample = document.getElementById(sample);
if(sample.style.backgroundColor == 'red'){
return 'false';
}
else{
return 'true';
}
}
</script>
<input type='submit' id="sub" name ="submit" value='Update Samples' />
</form>
test example of check_form function that does work:
function check_form(){
sample = document.getElementById(sample);
return 'false';
}
Edit: The way I have my form set up now is more accurately displayed as:
<!DOCTYPE html>
<html>
<body>
<?php $sample = 'test'; ?>
<form class="bulk" onsubmit="return validate(this)" action="next_page.php" method="GET">
<input type="checkbox" id="checkbox" name ="checkbox">
<input type="text" id="<?php echo $sample;?>" name="<?php echo $sample;?>" value="">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var checkbox_name = 'checkbox';
sample = <?php echo json_encode("$sample"); ?>;
sample = document.getElementById(sample);
//if checkbox is checked, make sure all the required fields are there
$("#"+checkbox_name).change(function(){
if(document.getElementById(checkbox_name).checked){
sample.style.backgroundColor = "red";
}
});
});
function validate(from) {
var valid = 'true';
if(check_form() == 'false'){
valid = 'false';
}
if(valid == 'false'){
alert('ERROR: Some inputs are invalid. Please check fields');
return false;
}
else{
return confirm('Are you sure you want to submit?');
}
}
function check_form(){
sample = document.getElementById(sample);
console.log(sample.style.backgroundColor)
if (sample.style.backgroundColor == 'red') {
return 'false';
} else {
return 'true';
}
}
</script>
<input type='submit' id="sub" name ="submit" value='Update Samples' />
</form>
Where the samples are brought in from another page to dynamically create the form.
sample is a local variable in the dom ready handler which is not accessible in the check form method, but since sample is an id of an element that will be available as a window property(global variable), so you will be getting an error like Uncaught TypeError: Cannot read property 'style' of null.
Instead pass the id as a string literal in the check_form method like
function check_form() {
var sample = document.getElementById('sample');
console.log(sample.style.backgroundColor)
if (sample.style.backgroundColor == 'red') {
return 'false';
} else {
return 'true';
}
}
Demo: Fiddle

Form Validation not working on all fields but only the first

When i post form only the title validation is working, the other two fields are not validated.
HTML
<form name="qaform" class="nice" method="POST" onsubmit="validateForm()" action="/ask/ask-question/">
<input type="hidden" id="id_selected_tags" name="tags">
<p>
<label for="id_title" class="inline-block">Title</label>
<input type="text" class="input-text inline-block" id="id_title" name="question_title">
</p>
<span id="error_title"></span>
<textarea id="id_question" name="question_description" class="full-width"></textarea>
<span id="error_body"></span>
<p>
<label for="id_tags" class="inline-block">Tags</label>
<input type="text" id="id_newstagbox" name="question_tags"/>
</p>
<span id="error_tags"></span>
<button class="btn btn-success" type="submit">Post your question</button>
</form>
JS
function validateForm()
{
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
return false;
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
return false;
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
return false;
}
}
After submitting the forms post successfully if title is present.
The stackoverflow form validation forced me to do this, its constantly saying me to add more text because my question contains mostly code.I know its good to provide more information about question but there are times when you can ask a question in few words without being too broad and then you have to rant about it to pass the FORM VALIDATION.
Just remove return false.modify it like below
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["farea"].value;
var z=document.forms["myForm"]["ftag"].value;
if (x==null || x=="")
{
document.getElementById('ern').innerHTML="*Please add a title*";
}
if (y==null || y=="")
{
document.getElementById('era').innerHTML="*Please add a desxription*";
}
if (z==null || z=="")
{
document.getElementById('ert').innerHTML="*Please add a tag*";
}
}
</script>
I prefer using jQuery:
$('#form').submit(function(e) {
var validated = true;
e.preventDefault();
//title validation
if ($('#id_title').val() == "") {
$('#error_title').html("*Please add a title*");
validated = false;
}
//body validation
if ($('#id_question').val() == "") {
$('#error_body').html("*Please add a description*");
validated = false;
}
//tag validation
if ($('#id_newstagbox').val() == "") {
$('#error_tags').html("*Please add a description*");
validated = false;
}
if(validated) {
$(this).unbind('submit').submit();
}
});
You just remove your return false inside each condition,
check this jsfiddle how it works if you remove return false line.
Note:Return false will stop your execution there
Remove the "return false" in the if clauses. This stops your function and the other if clauses wouldn´t get called.
just add 'return' keyword before validateform()
like this
<form name="qaform" class="nice" method="POST" onsubmit="return validateForm()" action="/ask/ask-question/">
Try making these 5 small changes to your validateForm method -
function validateForm() {
var valid = true; // 1
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
valid = false; // 2
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
valid = false; // 3
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
valid = false; // 4
}
return valid; // 5
}
i think the reason why it only validates the first one, is because you return false to exit the validate function, if you do the return false after all the if loops i think it will do what you want.

javascript return true not working

i have used the following code for javascript validation, that return true or false depending on the condition
javascript block
function fnval()
{
if(document.field.value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
Here is my HTML:
<Input type=submit name="sub" onClick="return fnval()">
Thus the js block checks if the field value is entered or not. If not it throws an alert message and return false, and hence the form does not get submitted.
But in case the value is not empty it returns a true, and still the form does not get submitted.
I have seen some queries asked by people where return false results in submission of the form. But this is exactly opposite.. and am not able to find a solution as of now.
Can anyone please help me on this?
Try getElementsByName:
function fnval()
{
if(document.getElementsByName('field')[0].value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
getElementsByName doesn't have IE support though. Perhaps:
function fnval()
{
if(findInput('field')[0].value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
function findInput(name) {
var elements = document.getElementsByTagName('input'),
length = elements.length,
i = 0,
results = [];
for(i; i<length; i++) {
if (elements[i].name === name) {
results.push(elements[i]);
}
}
return results;
}
You need to add the form name and the form value. Something like:
if ( document.formName.fieldName.value == "" )
For instance, with this kind of HTML:
<form method="post" onsubmit="">
Password: <input name="password" type="text" /><br />
</form>
The js:
if (document.form.password.value == "") {
//empty
}
i suggest using onsubmit in the form, <form ... onsubmit="return fnval()">,
try adding that and placing return false at the base of your function.
no matter what you do in js. but if you have filled action tag of form element element , the form will submit.
Syntax error:
type="submit"
not
type=submit

Categories