Validation values - javascript

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

Related

JS Function is invoked but no result

When I invoke the function it is getting invoked but it flashes the result. Could please tell me what is the mistake I did?
Below is the HTML Code I used:
I have replaced the input type as a button but still, error not fixed.
function reg() {
//Name Field
var f = document.forms["registration"]["fullname"].value;
if (f == "") {
alert("Enter the name");
return false;
} else if (!f.match(/^.[a-zA-Z]+$/))
{
alert("Enter only alphabets");
return false;
}
document.getElementById('details').innerHTML = "Hi" + registration.fullname.value;
}
<form name="registration" onsubmit="return reg()">
<input type="text" name="fullname" placeholder="Enter Your Full Name"><br><br>
<input type="submit" value="submit">
</form>
Here is what I believe you want to do.
Note it is better to add an event handler in the script rather than having an inline handler, but for now I pass the form itself in the function
function reg(form) {
//Name Field
var f = form.fullname.value;
if (f == "") {
alert("Enter the name");
return false;
}
// no need for else when you return
if (!f.match(/^[\. a-zA-Z]+$/)) { // I personally have a space in my full name
alert("Enter only alphabets and space");
return false;
}
document.getElementById('details').innerHTML = "Hi " + f;
// change to true if you want to submit the form but you will then not be able to see the HI
return false;
}
<form name="registration" onsubmit="return reg(this)">
<input type="text" name="fullname" placeholder="Enter Your Full Name"><br><br>
<input type="submit" value="submit">
</form>
<span id="details"></span>

How can I validate with javascript and then submit data with php?

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

display message on wrong password entry

I have a submit button which only works when "victory" is typed into the form. Now I am trying to work on an error message to display "wrong keyword entry" if the text entered into the form field isn't "victory". here is the code
<form name="input" action="index.html" method="post" onsubmit="return check();">
<input type="text" maxlength="7" autocomplete="off" name="" id="victory">
<br><input type="submit" class="bigbutton" value="NEXT">
</form>
<script>
function check(){
if(document.getElementById("victory").value == "victory")
return true;
else
return false;
}
If I were you I'd add an HTML element to stuff an error into. Then you can style it with CSS however you'd like.
<div id="error"></div>
Then your function would look something like this:
function check(){
if(document.getElementById("victory").value == "victory")
return true;
else
document.getElementById("error").innerHTML = "Wrong keyword entry."
return false;
}
You can simply add the alert in the else condition…
function check(){
if(document.getElementById("victory").value == "victory") {
return true;
}
else {
alert("wrong keyword entry");
return false;
}
}

Form validation problems

I have a very strange problem. Inside form I have hidden input with value -1 and input field for username.
<form action="" method="POST" name="login" onSubmit="return Validate()">
<input type="text" id="username"/>
<input type="hidden" id="available" value="-1"/>
< input type="submit" value="Send"/>
</form>
On submit function Validate() checks value of username input which mustn't be empty, and Validate() also checks value of available input which mustn't be valued -1.
function Validate(){
var a=document.getElementById("username").value;
var b=document.getElementById("available").value;
if(a=="" || a==null)
{
alert("Username cannot be empty");
return false;
}
else if(b<0)
{
alert("Form isn't finished");
return false;
}
else
{
return true;
}
}
Problem is that Validate() works only if one condition is evalueted. If function Validate() contains only 1 var(a or b) and 1 if order(without else if) it works correctly. But when I put it like this, when Validate uses a and b variables and if, else if conditional order it won't work. Really od.. Thanks in advance...
In this case it works:
function Validate(){
var a=document.getElementById("username").value;
if(a=="" || a==null)
{
alert("Username cannot be empty");
return false;
}
else
{
return true;
}
}
<input type="hidden" id="available" value="-1"/>
Here the value is of string dataType. Whereas
else if(b<0) //b is string dataType
Hence it failed. so change it as
var b= Number(document.getElementById("available").value);
Try like this
HTML:
<form action="" method="POST" name="login">
<input type="text" id="username" />
<input type="hidden" id="available" value="1" />
<input type="button" value="Send" onClick="return Validate()" />
</form>
JS:
function Validate() {
var a = document.getElementById("username").value;
var b = Number(document.getElementById("available").value);
if (a == "" || a == null) {
alert("Username cannot be empty");
return false;
} else if (b < 0) {
alert("Form isn't finished");
return false;
} else {
document.login.submit(); //dynamically submit the form
}
}
If you are wanting to get error notifications for each input don't use if/else here, use multiple if's and set your errors
function validate(){
var a=document.getElementById("username").value;
var b=document.getElementById("available").value;
var errors = [];
if(a=="" || a==null){
errors.push("Invalid username");
}
if(b<0 || isNaN(b)){
errors.push("Invalid available value");
}
if(errors.length>0) {
//do something with errors (like display them
return false;
}
}
Using the else if one of them evaluates to true it will skip the others. For instance if the first one is empty or null then it will do that block and skip the others.
I was testing your code for IE and Firefox and it work. Just add parseInt when you get the value of var b.
var b= parseInt(document.getElementById("available").value);

stop form during submission if it validates incorrectly

I am trying to use JavaScript to validate forms but if the form doesn't validate, I don't want the form to be sent to the "action" page.
The validator:
<script>
function formSubmit()
{
document.getElementById("signup_form").submit();
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
The form itself:
<form action="some_file.php" method="post" id="signup_form" name="signup_form" onsubmit="return formSubmit()">
But all this does is if the tname field empty, it will return an alert but as soon as the user hits ok, the form then redirects to some_file.php. What have I missed here?
The submit button:
Signup
So what have I missed? How do I avoid this in the future?
You have the wrong execution of statememts. You are submitting the form before validating. Move this statement below the if statement
document.getElementById("signup_form").submit();
further to this. you are calling formSubmit() at two places, form tag and a tag doing it once is fine.
UPDATED CODE:
<html>
<head>
<title></title>
<script>
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
document.getElementById("signup_form").submit();
}
</script>
</head>
<body>
<form action="some_file.php" method="post" id="signup_form" name="signup_form" onsubmit="return formSubmit()">
<input type="text" name="tname" />
Signup
</body>
</html>
DEMO
Try this:
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (x=="")
{
alert("First name must be filled out");
return false;
}
return true;
}
*Changes made to your code: *
- There is no need for formSubmit to try to submit the form! Just perform the validation checks and return true if you want the submission to proceed or false otherwise.
Also you do not need to check for the x == null case. If the textbox is empty, its value will be "".
What might be needed though is a check that x does not just contain spaces. If you do not care about supporting older browsers you can use the new Javascript trim function. If you care about backwards compatibility, either try one of the many javascript libraries that offer trim or the following:
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value.replace(/^\s+|\s+$/g, '');
if (x=="")
{
alert("First name must be filled out");
return false;
}
return true;
}
If I just wanted to avoid submitting spaces I would have left the var x= bit as it was and added the replace in the check making it if(x.replace(/\s/g, '') == ""). However, I also want to trim the input so that if the user enters " user1" or "user1 " the form will send "user1".
You can see the three different versions versions working here:
http://jsfiddle.net/9LPfb/2/
http://jsfiddle.net/9LPfb/3/
http://jsfiddle.net/9LPfb/6/
you have problem with your program flow .
do validation before the submitting form.
there is no use of validating after submitting, i think you have mistakenly made it.
just submit after validation.
try:
function formSubmit() {
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else {
return true;
}
}
You already had all the code. It was becos of wrong execution.
<script>
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (!x){
alert("First name must be filled out");
return false;
}
return true;
}
</script>
<form action="some_file.php" method="post" id="signup_form" name="signup_form">
Signup
in your function just remove this line
document.getElementById("signup_form").submit();
and add it after the if condition
or rewrite the function like the one below
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}else
return true;
}
Contact Form
function empty() {
var x,y;
x = document.forms["ff"]"name"].value;
y = document.forms["ff"]["surname"].value;
if(x=="" ||x==null){
alert("Enter your name");
return false;
}else if(y==""){
alert("Enter your surname");
return false;
}else{
alert('Data is sending');
return true;
}
};
In the html:
<form method="POST" action="formdata.php" name="ff"onsubmit="return empty()">
<table>
<tr>
<td>Enter Your Name : <input type="text" name="name" maxlength="30" size="40" id="na" ></td>
</tr>
<tr>
<td>Enter Your Surname : <input type="text" name="surname" maxlength="30" size="40" id="sna"></td>
</tr>
<tr>
<td>
<input type="submit" name="formsubmit" value="submit" >
</td>
</tr>
</table>
</form>

Categories

Resources