JavaScript data validation - javascript

Please help me. The validation is not working:
<script type="text/javascript" src="javascript.js">
function validation()
{
var fname=document.forms["form1"]["fname"].value;
var lname=document.forms["form1"]["lname"].value;
var idnumber=document.forms["form1"]["idnumber"].value;
var email=document.forms["form1"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
var address=document.forms["form1"]["address"].value;
var phonenumber=document.forms["form1"]["phonenumber"].value;
if (fname==null || fname=="")
{
alert("Name should be entered correctly");
return false;
}
if (lname==null || lname=="")
{
alert("Name should be entered correctly");
return false;
}
if (isNaN(idnumber))
{
alert("Please enter a valid id number");
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid e-mail address");
return false;
}
if(address==null || address=="")
{
alert("Please insert your address");
return false;
}
if (isNaN(phonenumber))
{
alert("Please enter a valid phone number");
return false;
}
}
</script>
<form name="form1" action="validation.php" method="post" onsubmit=" return validation(this);return false">
Firstname:<input type="text" name="fname"><br/>
Lastname:<input type="text" name="lname"><br/>
Nation ID Number:<input type="text" name="idnumber" minlength="8"maxlength="8"><br/>
Email address: <input type="text" name="email"><br/>
Address:<input type="text" name="address"><br/>
Pnone number:<input type="text" name="phonenumber"><br/>
<input type="reset" name="reset" value="reset">
<input type="submit" name="submit" value="submit">
</form>

There are a number of issues with that code:
You really should not use the same <script> element for both calling src="javascript.js" and at the same time declare a function. Use separate elements, like this:
<script type="text/javascript" src="javascript.js"></script>
<script type="text/javascript">
function validation()
{
...
}
</script>
In the <form> element, there's a redundant ;return false. The form will take the value from return validation(this), anything after it will be ignored. Also, no need of ";" when using in-line javascript.
You are passing passing this as argument to the validation() function, but validation is expecting no argument. Should be:
function validation(oForm)
If you are already passing this, why not use it? this is a reference to the element itself, so it is, for the validation function, a reference to the form. So no need to name the form.
<form action="validation.php" method="post" onsubmit="return validation(this)">
And the references in function would be:
function validation(oForm)
{
var fname=oForm["fname"].value;
var lname=oForm["lname"].value;
}
Those changes alone could solve your problem. I'll check the code further to see if there is something else.
EDIT:
I've tested the validation now, and it works. The only required modification is removing the scr=validation.js from your <SCRIPT> tag. Use separate tags for that, as i suggested.
But i strongly suggest you consider the other issues I've mentioned.
Also, other suggestions regarding the validation itself:
For alphanumerical fields, no need to check for null, only "" is enough. You can simply use:
if (lname=="")
First Name and Last Name error messages are the same. That will confuse users.
Avoid testing phone numbers as numeric. Remember "(407) 234-5678" is a perfectly valid phone number, although it will fail your test. Unless you have a strong reason to treat it as numeric (automatic dialing?), leave it as an ordinary, text field.
In the National ID field: There is no minlength in HTML. Only maxlength
isNaN(idnumber) will return true if value is blank. And also if length<8. I assume it is a required field with a required length, so you should use:
if (isNaN(idnumber) || idnumber.length != 8)
{
alert("Please enter a valid id number");
return false;
}
For all your tests, consider trimming the values. Currently, input like " " (blanks only) WILL pass your test. Javascript has no built-in trim function, but it can be done with this:
function trim( texto ) {
return texto.replace(/^\s*|\s*$/g, "");
}
And used like this:
var fname=trim(oForm["fname"].value);
For clarity, use an explicit return true; in validation() after all tests successful.
Here is the suggested code after all changes:
<script type="text/javascript" scr="validation.js"></script>
<script type="text/javascript">
function validation(oForm)
{
var fname = trim(oForm["fname"].value);
var lname = trim(oForm["lname"].value);
var idnumber = trim(oForm["idnumber"].value);
var email = trim(oForm["email"].value);
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
var address = trim(oForm["address"].value);
var phonenumber = trim(oForm["phonenumber"].value);
if (fname=="")
{
alert("First name should be entered");
return false;
}
if (lname=="")
{
alert("Last name should be entered");
return false;
}
if (isNaN(idnumber) || idnumber.length != 8)
{
alert("Please enter a valid id number");
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid e-mail address");
return false;
}
if(address=="")
{
alert("Please insert your address");
return false;
}
if (isNaN(phonenumber))
{
alert("Please enter a valid phone number");
return false;
}
return true;
}
function trim( texto ) {
return texto.replace(/^\s*|\s*$/g, "");
}
</script>
<form name="form1" action="validation.php" method="post" onsubmit="return validation(this)">
Firstname:<input type="text" name="fname"><br/>
Lastname:<input type="text" name="lname"><br/>
Nation ID Number:<input type="text" name="idnumber" maxlength="8"><br/>
Email address: <input type="text" name="email"><br/>
Address:<input type="text" name="address"><br/>
Pnone number:<input type="text" name="phonenumber"><br/>
<input type="reset" name="reset" value="reset">
<input type="submit" name="submit" value="submit">
</form>

Related

How do I check if input is blank/not blank and do specific thing

Okay so I know this is probably a headache for most of you but i'm having trouble figuring this out as javascript is not my strong suit.
I'm trying to basically get this one page to load if username and password is not blank but if it is blank I want it to alert to me (specifically window.alert()) that I have not inputted username and/or password.
I cannot seem to figure it out so here it is.
<button type="submit" id="enterButton" onclick="newPage()"><strong>Enter</strong></button>
there is my button where I put my function on
var username = getElementById("userName");
var password = getElementById("passWord");
function newPage() {
if(username.val().length==0 || password.val().length==0){
alert("please enter valid information");
return location.href = "newPage.html";
}
else{
location.href = "newPage.html";
}
}
and here is my failed attempt to initialize my idea.
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if (password==null || password==""){
alert("password can't be blank");
return false;
} else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
<html>
<body>
<body>
<form name="myform" method="post" action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
Try to check first if you can get the value of your username. If you're using plain javascript, you should use document.getElementById("userName").value.

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>

Validating a form in Javascript not working

I'm trying to validate a form using JavaScript, but the code doesn't seem to execute. The Form is being processed using php which is working just fine. But, the validation is not working. Can someone please help me with this.
<script>
function validateForm(){
var x = document.getElementById('name');
var email = document.getElementById('email');
var num = document.getElementById('number');
var size = document.getElementById('size');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var atpos=email.value.indexOf("#");
var dotpos=email.value.lastIndexOf(".");
if (x.value == null || x.value == "") {
alert("Please Enter your name");
x.foucs;
x.style.background = 'Yellow';
return false;
}
if(!filter.test(email.value){
alert('Please provide a valid email address');
email.focus;
email.value="";
return false;
}
if(num.value == null && num.value == ""){
alert('Please enter your mobile number');
num.focus();
}
if(!isNan(num.value){
alert('Please enter a valid number');
num.focus();
num.style.background();
return false;
}
return false;
}
</script>
And here is my html code.
<form method="post" name="myForm " onsubmit="return validateForm()" action="myprocessingscript.php" >
<input type="text" name="name" placeholder="Name" class="text" id="name" />
<input name="email" placeholder="Email" type="text" class="text" id="email"/>
<input name="number" placeholder="Mobile Number" type="text" class="text" id="number"/>
<input name="size" placeholder="Size" type="text" class="text" id="size" />
<input type="Submit" value="Submit" class="button">
Working fiddle
Correct the spelling of foucs and ensure all references have parenthesis such as:
email.focus();
Without parenthesis, the function is not called. It's valid Javascript but it won't do anything.
You also missed a closing ) here:
if(!filter.test(email.value){
// ^ add another )
and here:
if(!isNan(num.value){
// ^ add another )
!isNan(....) should be isNaN(....). Javascript is case sensitive and you shouldn't be "notting" it here. isNaN is saying "is not a number" so it's already "notted".
On the line below, style has no background function. Looks like you want to assign a value here not call a function:
num.style.background(); // change to assign value.
On this line, change && to ||:
if(num.value == null && num.value == ""){
// ^ should be ||
Finally, remove the return false at the end.
Try using x.focus();
x.foucs; is not a valid statement, and neither is email.focus;.
These aren't right I don't think:
email.focus;
// Try email.focus();
and
x.foucs;
// Try x.focus();
Also looking at your code I don't see a </form>
Try this:
function validateForm(){
var x = document.getElementById('name');
var email = document.getElementById('email');
var num = document.getElementById('number');
var size = document.getElementById('size');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (x.value == null || x.value == "") {
alert("Please Enter your name");
x.focus();
x.style.background = 'Yellow';
return false;
}
if(!filter.test(email.value){
alert('Please provide a valid email address');
email.focus();
email.value="";
return false;
}
if(num.value == null || num.value == ""){
alert('Please enter your mobile number');
num.focus();
return false;
}
if(!isNaN(num.value)){
alert('Please enter a valid number');
num.focus();
num.style.background = "Yellow";
return false;
}
return true;
}

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>

Why won't this javascript phone field form validator work?

This phone number validator doesn't work :/. Why?
Ideally, if the optional phone field is not null, it should proceed to validate the form.
The phone field is optional, and isn't required.
Validating the form:
the phone field is optional. this means that it is not required.
it should ignore comparing everything except numbers.
if the digit count is != 10 numbers, it should display the error.
if the count is equal to 10 digits, it should pass onto name.php (see the HTML)
Javascript Code:
function validateForm() {
var x=document.forms["form"]["name"].value;
if (x==null || x=="")
{
alert("Name is required.");
return false;
}
var y=document.forms["form"]["email"].value;
var atpos=y.indexOf("#");
var dotpos=y.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=y.length)
{
alert("Valid email required.");
return false;
}
var formValue = document.forms["form"]["number"].value;
var regExpressionValue = /[^\d.]/g;
if (formValue !== null)
{
if (regExpressionValue.test(formValue) !== true)
{
alert("Optional phone number invalid. Example: [1234567890].");
return false;
}
}
return true;
}
HTML:
<form class="form" id="form" name="form" method="post" action="name.php" onsubmit="return validateForm()" />
<input type="text" name="name" id="name" />
<input type="text" name="email" id="email" />
<input type="tel" name="number" id="number" />
<button type="submit" value="Send" />Sign Up</button>
<div class="spacer"></div>
</form>
Your regular expression is wrong. Try this instead
if (/^\d{10}$/.test(formValue) === false) {
alert("Optional phone number invalid. Example: [1234567890].");
return false;
}
You have bad regexp and string presence check for phone number. Check this out:
function validateForm() {
var x=document.forms["form"]["name"].value;
if (x==null || x=="")
{
alert("Name is required.");
return false;
}
var y=document.forms["form"]["email"].value;
var atpos=y.indexOf("#");
var dotpos=y.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=y.length)
{
alert("Valid email required.");
return false;
}
var formValue = document.forms["form"]["number"].value;
if (formValue)
{
var regExpressionValue = /^(\d-?){10}$/g;
if (regExpressionValue.test(formValue) !== true)
{
alert("Optional phone number invalid. Example: [1234567890].");
return false;
}
}
return true;
}

Categories

Resources