0

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

nickb
  • 59,313
  • 13
  • 108
  • 143
JLearner
  • 1,271
  • 9
  • 27
  • 40

3 Answers3

1

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

}
Wern Ancheta
  • 22,397
  • 38
  • 100
  • 139
0

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.

Robert
  • 2,441
  • 21
  • 12
0

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()

Community
  • 1
  • 1
Lorenz
  • 1,263
  • 9
  • 20
  • i have my isNumeric function for that. Now the issue is it wont call my function. It straight away goes to nextpage.php – JLearner Jul 18 '12 at 13:49