Data Validation for text and number in Javascript - javascript

I would like to have a form where it asks for a user's name, phone number and email address. The name field should only contain letters, the phone number field should only contain numbers and the email field should contain '#'. The form needs to be validated using Javascript. The validation should happen when the user clicks on submit. Can someone help? Please look at my existing code:
HTML:
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Contact</title>
<script src="datavalidation.js"></script>
</head>
<body onload="document.registration.userid.focus();">
<section>
<h1>Contact</h1></br>
<h2>To get in contact with us please fill out the contact form below</h2></br>
<p>Fill in all of the boxes below and click the 'Submit' button to submit message and one of our team will get back in touch with you within 48 hours</p></br>
<form name='registration' onSubmit="return formValidation();">
<ul>
<li><label for="username">Name:</label></li>
<li><input type="text" name="username" size="50" /></li>
<li><label for="number">Phone No:</label></li>
<li><input type="text" name="number" /></li>
<li><label for="email">Email:</label></li>
<li><input type="text" name="email" size="50" /></li>
<li><label for="desc">Message:</label></li>
<li><textarea name="desc" id="desc"></textarea></li>
<li><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
</section>
Javascript:
function formValidation()
{
var uname = document.registration.username;
var unumber = document.registration.number;
var uemail = document.registration.email;
{
if(allLetter(uname))
{
if(allnumeric(unumber))
{
if(ValidateEmail(uemail))
}
}
}
return false;
function allLetter(uname)
{
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function allnumeric(unumber)
{
var numbers = /^[0-9]+$/;
if(unumber.value.match(numbers))
{
return true;
}
else
{
alert('Phone number must have numeric characters only');
unumber.focus();
return false;
}
}
function ValidateEmail(uemail)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(uemail.value.match(mailformat))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
return false;
}
else
{
alert('Form Succesfully Submitted');
window.location.reload()
return true;
}
}
}
Please help!

function formValidation()
{
var uname = document.registration.username;
var unumber = document.registration.number;
var uemail = document.registration.email;
if(allLetter(uname))
{
if(allnumeric(unumber))
{
ValidateEmail(uemail)
}
}
function allLetter(uname)
{
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function allnumeric(unumber)
{
var numbers = /^[0-9]+$/;
if(unumber.value.match(numbers))
{
return true;
}
else
{
alert('Phone number must have numeric characters only');
unumber.focus();
return false;
}
}
function ValidateEmail(uemail)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(uemail.value.match(mailformat))
{
alert('Form Succesfully Submitted');
window.location.reload();
return true;
}
else
{
alert("You have entered an invalid email address!");
return false;
}
}
}
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Contact</title>
<script src="datavalidation.js"></script>
</head>
<body>
<section>
<h1>Contact</h1></br>
<h2>To get in contact with us please fill out the contact form below</h2></br>
<p>Fill in all of the boxes below and click the 'Submit' button to submit message and one of our team will get back in touch with you within 48 hours</p></br>
<form name='registration' onSubmit="return formValidation();">
<ul>
<li><label for="username">Name:</label></li>
<li><input type="text" name="username" size="50" /></li>
<li><label for="number">Phone No:</label></li>
<li><input type="text" name="number" /></li>
<li><label for="email">Email:</label></li>
<li><input type="text" name="email" size="50" /></li>
<li><label for="desc">Message:</label></li>
<li><textarea name="desc" id="desc"></textarea></li>
<li><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
</section>

Related

Why does my JavaScript seems to not run in my HTML

Sorry for any formatting error, first time posting.
Sorry if similar of this is already answered, I couldn't find it anywhere (or I'm just bad at searching).
I'm doing a page to register user to my website, my javascript doesn't work and I can't find what's wrong with it.
My html file does not display the alertbox which supposed to run if I leave my box empty, putting in the wrong characters, etc.
registration.html
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="utf-8">
<title>Registration Form</title>
</head>
<body onLoad="document.registration.userID.focus();">
<h1>Registration Form</h1>
<form name="registration" onSubmit="return validation();">
<label for="userID">User ID</label><br><input id="userID" name="userID" placeholder="Enter your ID" type="text"/><br>
<label for="userPass">Password</label><br><input id="userPass" name="userPass" placeholder="Enter your password" type="password" /><br>
<label for="userName">Username</label><br><input id="userName" name="userName" placeholder="Enter your username" type="text" /><br>
<label for="addr">Address</label><br><input id="addr" name="addr" placeholder="eg. Tamara Residence" type="text" /><br>
<label for="ctry">Country</label><br><select id="ctry" name="ctry">
<option value="DEF">Please select your country</option>
<option value="MY">Malaysia</option>
<option value="IN">India</option></select><br>
<label for="zip">Zip Code</label><br><input id="zip" name="zip" placeholder="eg. 25565" type="text" /><br>
<label for="email">Email</label><br><input id="email" name="email" placeholder="eg. nikfarisaiman109#gmail.com" type="text" /><br>
Sex<br>
<input type="radio" id="1" name="sex" value="1">
<label for="1">Male</label><br>
<input type="radio" id="2" name="sex" value="2">
<label for="2">Female</label><br>
Language<br>
<input type="checkbox" id="EN" name="EN" value="English">
<label for="EN">English</label><br>
<input type="checkbox" id="MY" name="MY" value="Malay">
<label for="MY">Malay</label><br>
<label for="about">About</label><br>
<textarea id="about" name="about" rows="4" cols="50">
</textarea><br><br>
<input name="submit" type="submit" value="Register" />
</form>
<script src="formValidation.js" type="text/javascript"></script>
</body>
</html>
formValidation.js
function validation(){
var userID = document.registration.userid;
var userPass = document.registration.password;
var userName = document.registration.name;
var addr = document.registration.address;
var ctry = document.registration.country;
var zip = document.registration.zip;
var email = document.registration.email;
var sex = document.registration.sex;
if (userID_validate(userID,5,12)) {
if (userPass_validate(userPass,7,12)) {
if (alphabet_validate(userName)) {
if (alphanumeric_validate(addr)) {
if (empty_validate(ctry)) {
if (allnumeric_validate(zip)) {
if (emailformat_validate(email)) {
if (sex_validate(sex)) {
}
}
}
}
}
}
}
}
return false;
}
function userID_validate(userID,a,b) {
//length of string
var userID_length = userID.value.length;
if (userID_length == 0 || userID_length >= a || userID_length < b) {
alert("ID should not be empty / length should be between " + a + " to " + b + " characters");
userID.focus();
return false;
}
return true;
}
function userPass_validate(userPass,a,b) {
//length of string
var userPass_length = userPass.value.length;
if (userPass_length == 0 || userPass_length >= a || userPass_length < b) {
alert("Password should not be empty / length should be between " + a + " to " + b + " characters");
userPass.focus();
return false;
}
}
function alphabet_validate(userName) {
var betReg = /^[A-Za-z]+$/;
if (userName.value.match(betReg)) {
return true;
}
else {
alert("Username should only contain alphabet");
userName.focus();
return false;
}
}
function alphanumeric_validate(addr) {
var betnumReg = /^[0-9A-Za-z]+$/;
if (addr.value.match(betnumReg)) {
return true;
}
else {
alert("Address can only be alphanumeric");
addr.focus();
return false;
}
}
function empty_validate(ctry) {
if(ctry.value == "DEF"){
alert("Please select a country");
ctry.focus();
return false;
}
else
return true;
}
function allnumeric_validate(zip) {
var numReg = /^[0-9]+$/;
if (zip.value.match(numReg)) {
return true;
}
else {
alert("ZIP Code should only contain only numbers");
zip.focus();
return false;
}
}
function emailformat_validate(email) {
var emailReg = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if(email.value.match(emailReg))
return true;
else {
alert("Please enter in a correct email address format");
email.focus();
return false;
}
}
function sex_validate(sex) {
var formValid = false;
var x = 0;
while (!formValid && x < document.getElementById("sex").length) {
if (document.getElementById("sex")[x].checked)
formValid = true;
x++;
}
if (!formValid){
alert("Please select male or female");
sex.focus();
return false;
}
else {
alert("Form successfully submitted, thank you for registering!");
window.location.reload();
return true;
}
}
Did you check the error on Console via doing Inspect Element? I copied the same code as you mentioned in Question and getting this error in Console.
Uncaught TypeError: userID is undefined
In your formValidation.js, please update the
var userID = document.registration.userid;
With correct userID as follow.
var userID = document.registration.userID;
Try putting the <script> into <head>

Basic HTML-Javascript based form validation

I am very new to js and html, could someone help me understand as to why my page is getting redirected to the next page even if the validation fails and my "validate()" function returns only FALSE!
I have created a form that takes name, age, email, state etc as input and it should ideally validate them and then proceed towards the next page.
Here is the code :
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript">
function validate(){
var name=document.getElementById('name_id').value;
var email=document.getElementById('email_id').value;
var age=document.getElementById('age_id').value;
var state=document.getElementById('state_id').value;
var address=document.getElementById('address_id').value;
//checking conditions for name
if (name_length<10)
{
return false;
}
if(!(/\w \w/.test(name2)))
{
alert("Please enter name correctly!");
return false;
}
if(/\d/.test(name2))
{
alert("Name cannot contain digits");
return false;
}
//checking conditions for email
var index_of_at = name.indexOf('#');
if(index_of_at == -1)
{
alert("Please enter a valid email address");
return false;
}
else
{
var befor_at = email.substring(0,index_of_at);
var after_at =email.substring(index_of_at+1,email.length);
if(!(/[!-$?]/.test(before_at)))
{
if((/(\w|\d|.)/).test(before_at))
continue;
else
{
alert("Please enter a valid email address");
return false;
}
}
else
{
alert("Please enter a valid email address");
return false;
}
}
//checking conditions for age
if(/\w/.test(age))
{
alert("Please enter a valid Age");
return false;
}
else
{
if(age>100 || age<0)
{
alert("Please enter age btetween 0 and 100");
return false;
}
}
return false;
}
</script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" method="post" onsubmit="return validate();">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
</body>
</html>
Could somebody please help me with why my code redirects directly to handle.html without checking for validations?
You're trying to get the length of name as follow: name_length this is a typo, however, you have another error: a continue keyword
if((/(\w|\d|.)/).test(before_at))
continue;
^
else
Changed to:
if((/(\w|\d|.)/).test(before_at)) {
//continue; You need to modify this part.
} else {
alert("Please enter a valid email address");
return false;
}
You need to understand that continue keyword must be placed within a loop, i.e: for-loop.
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript">
function validate(e){
var name=document.getElementById('name_id').value;
var email=document.getElementById('email_id').value;
var age=document.getElementById('age_id').value;
var state=document.getElementById('state_id').value;
var address=document.getElementById('address_id').value;
//checking conditions for name
if (name.length<10)
{
alert('Please enter name correctly!');
return false;
}
if(!(/\w \w/.test(name2)))
{
alert("Please enter name correctly!");
return false;
}
if(/\d/.test(name2))
{
alert("Name cannot contain digits");
return false;
}
//checking conditions for email
var index_of_at = name.indexOf('#');
if(index_of_at == -1)
{
alert("Please enter a valid email address");
return false;
}
else
{
var befor_at = email.substring(0,index_of_at);
var after_at =email.substring(index_of_at+1,email.length);
if(!(/[!-$?]/.test(before_at)))
{
if((/(\w|\d|.)/).test(before_at)) {
//continue;
} else
{
alert("Please enter a valid email address");
return false;
}
}
else
{
alert("Please enter a valid email address");
return false;
}
}
//checking conditions for age
if(/\w/.test(age))
{
alert("Please enter a valid Age");
return false;
}
else
{
if(age>100 || age<0)
{
alert("Please enter age btetween 0 and 100");
return false;
}
}
return false;
}
</script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" method="post" onsubmit="return validate(event);">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
</body>
</html>
If you want to start learning web development with html and javascript, i suggest learn shortest way to do it. For javascript validation check this jquery validation
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" name="userForm" id="userForm" method="post">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
<script type="text/javascript">
$('#userForm').validate({
rules: {
name :{
required : true
},
email: {
required : true,
email : true,
},
age: {
required: true,
minlength:18, // Can define minimum age
maxlength:60 // max page
}
},
submitHandler: function(form) {
alert("All Well") ;
$("#userForm").submit(); // form tag id to sumit the form
return false ;
}
});
</script>
</body>
</html>
With jquery validation you can lots too much work with very short hand code.
Hope this will help, All the best.

How to keep the values on a registration form in html & javascript

So I am trying to create a registration form on a website with some basic html and javascript, and after figuring I made a short checker if both passwords were the same.
But whenever I press on submit all the values of the fields disappear how can I fix this?
I tried searching it on the web but it didnt help.
<form id="registerform" onsubmit=" return validateForm()">
First name:<br>
<label>
<input type="text" required="required" name="getfirstname">
</label><br>
Prefix:<br>
<input type="text" name="prefix"><br>
Last name:<br>
<input type="text" required="required" name="lastname"><br>
Email address:<br>
<input type="email" required="required" name="email"><br>
Password:<br>
<input type="password" required="required" name="password"><br>
Password2:<br>
<input type="password" required="required" name="password2"><br>
<input type="submit" value="Submit">
</form>
function validateForm() {
var x = document.forms["registerform"]["password"].value;
var y = document.forms["registerform"]["password2"].value;
if (y != x){
alert("The passwords do not match. Please try again!");
return false;
}
}
There are a few ways, for one you can submit the form with an AJAX request, save the data then fill it back in as soon as the form was submitted.
But why would you want to do this? What the user fills in should be cleared on submit.
If you just want to see the name of the input after you submit just use the placeholder tag, it can display a text in an input, clear that text when you start typing, and put it back when the form is empty:
<input placeholder="text">
you just have to specify that it is a javascript's function with tag ...
<script>
function validateForm() {
var x = document.forms["registerform"]["password"].value;
var y = document.forms["registerform"]["password2"].value;
if (y != x){
alert("The passwords do not match. Please try again!");
return false;
}
}
</script>
function formValidation()
{
var uid = document.registration.userid;
var passid = document.registration.passid;
var uname = document.registration.username;
var uadd = document.registration.address;
var ucountry = document.registration.country;
var uzip = document.registration.zip;
var uemail = document.registration.email;
var umsex = document.registration.msex;
var ufsex = document.registration.fsex; if(userid_validation(uid,5,12))
{
if(passid_validation(passid,7,12))
{
if(allLetter(uname))
{
if(alphanumeric(uadd))
{
if(countryselect(ucountry))
{
if(allnumeric(uzip))
{
if(ValidateEmail(uemail))
{
if(validsex(umsex,ufsex))
{
}
}
}
}
}
}
}
}
return false;
} function userid_validation(uid,mx,my)
{
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx)
{
alert("User Id should not be empty / length be between "+mx+" to "+my);
uid.focus();
return false;
}
return true;
}
function passid_validation(passid,mx,my)
{
var passid_len = passid.value.length;
if (passid_len == 0 ||passid_len >= my || passid_len < mx)
{
alert("Password should not be empty / length be between "+mx+" to "+my);
passid.focus();
return false;
}
return true;
}
function allLetter(uname)
{
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function alphanumeric(uadd)
{
var letters = /^[0-9a-zA-Z]+$/;
if(uadd.value.match(letters))
{
return true;
}
else
{
alert('User address must have alphanumeric characters only');
uadd.focus();
return false;
}
}
function countryselect(ucountry)
{
if(ucountry.value == "Default")
{
alert('Select your country from the list');
ucountry.focus();
return false;
}
else
{
return true;
}
}
function allnumeric(uzip)
{
var numbers = /^[0-9]+$/;
if(uzip.value.match(numbers))
{
return true;
}
else
{
alert('ZIP code must have numeric characters only');
uzip.focus();
return false;
}
}
function ValidateEmail(uemail)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(uemail.value.match(mailformat))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
uemail.focus();
return false;
}
} function validsex(umsex,ufsex)
{
x=0;
if(umsex.checked)
{
x++;
} if(ufsex.checked)
{
x++;
}
if(x==0)
{
alert('Select Male/Female');
umsex.focus();
return false;
}
else
{
alert('Form Succesfully Submitted');
window.location.reload()
return true;
}
}
h1 {
margin-left: 70px;
}
form li {
list-style: none;
margin-bottom: 5px;
}
form ul li label{
float: left;
clear: left;
width: 100px;
text-align: right;
margin-right: 10px;
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:14px;
}
form ul li input, select, span {
float: left;
margin-bottom: 10px;
}
form textarea {
float: left;
width: 350px;
height: 150px;
}
[type="submit"] {
clear: left;
margin: 20px 0 0 230px;
font-size:18px
}
p {
margin-left: 70px;
font-weight: bold;
}
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="utf-8">
<title>JavaScript Form Validation using a sample registration form</title>
<meta name="keywords" content="example, JavaScript Form Validation, Sample registration form" />
<meta name="description" content="This document is an example of JavaScript Form Validation using a sample registration form. " />
<link rel='stylesheet' href='js-form-validation.css' type='text/css' />
<script src="sample-registration-form-validation.js"></script>
</head>
<body onload="document.registration.userid.focus();">
<h1>Registration Form</h1>
<p>Use tab keys to move from one input field to the next.</p>
<form name='registration' onSubmit="return formValidation();">
<ul>
<li><label for="userid">User id:</label></li>
<li><input type="text" name="userid" size="12" /></li>
<li><label for="passid">Password:</label></li>
<li><input type="password" name="passid" size="12" /></li>
<li><label for="username">Name:</label></li>
<li><input type="text" name="username" size="50" /></li>
<li><label for="address">Address:</label></li>
<li><input type="text" name="address" size="50" /></li>
<li><label for="country">Country:</label></li>
<li><select name="country">
<option selected="" value="Default">(Please select a country)</option>
<option value="AF">Australia</option>
<option value="AL">Canada</option>
<option value="DZ">India</option>
<option value="AS">Russia</option>
<option value="AD">USA</option>
</select></li>
<li><label for="zip">ZIP Code:</label></li>
<li><input type="text" name="zip" /></li>
<li><label for="email">Email:</label></li>
<li><input type="text" name="email" size="50" /></li>
<li><label id="gender">Sex:</label></li>
<li><input type="radio" name="msex" value="Male" /><span>Male</span></li>
<li><input type="radio" name="fsex" value="Female" /><span>Female</span></li>
<li><label>Language:</label></li>
<li><input type="checkbox" name="en" value="en" checked /><span>English</span></li>
<li><input type="checkbox" name="nonen" value="noen" /><span>Non English</span></li>
<li><label for="desc">About:</label></li>
<li><textarea name="desc" id="desc"></textarea></li>
<li><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
</body>
</html>
Change
<form id="registerform" onsubmit=" return validateForm()">
to
<form id="registerform" name="registerform" onsubmit=" return validateForm()">
to access form controls by name like in document.forms["registerform"]["password"] and ensure your javascript code is inside a script tag and returns true if validation is Ok.
<script>
function validateForm() {
var x = document.forms["registerform"]["password"].value;
var y = document.forms["registerform"]["password2"].value;
if (y != x){
alert("The passwords do not match. Please try again!");
return false;
}
return true;
}
</script>
https://jsfiddle.net/FranIg/pxgcbtLo/

onsubmit() form on mobile browser

I current use a javascript function on the onsubmit() event of my form to check if all the input are not empty.
This works fine on computer, but on mobile phone, it changes the background color (as I want to do when the input is empty) but it still submits the form !!!
My form :
<form id="formContact" action="envoi-message.php" method="post" class="normal" onsubmit="return valideChamps();">
<div class="ddl">
<span>VOUS ÊTES...</span>
<div class="ddlOption">
<ul>
<li onclick="ddlContact('entreprise')"><span>UNE ENTREPRISE</span></li>
<li onclick="ddlContact('ecole')"><span>UNE ÉCOLE</span></li>
<li onclick="ddlContact('personne')"><span>UNE PERSONNE</span></li>
</ul>
</div>
</div>
<input class="cache" type="text" name="entreprise" placeholder="NOM DE L'ENTREPRISE" />
<input class="cache" type="text" name="ecole" placeholder="NOM DE L'ÉCOLE" />
<input type="text" name="nom" placeholder="VOTRE NOM" />
<input type="email" name="email" placeholder="VOTRE EMAIL" />
<textarea name="message" placeholder="VOTRE MESSAGE" ></textarea>
<input id="btnEnvoi" type="submit" value="Envoyer">
</form>
My function :
function valideChamps(){
var bResult = true;
if ($("input[name*='nom']").val() == "") {
$("input[name*='nom']").addClass("error");
bResult = false;
} else {
$("input[name*='nom']").removeClass("error");
}
if ($("input[name*='email']").val() == "") {
$("input[name*='email']").addClass("error");
bResult = false;
} else {
var regex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (regex.test($("input[name*='email']").val()) == false ) {
$("input[name*='email']").addClass("error");
bResult = false;
} else {
$("input[name*='email']").removeClass("error");
}
}
if ($("#formContact textarea").val() == ""){
$("#formContact textarea").addClass("error");
bResult = false;
}else {
$("#formContact textarea").removeClass("error");
}
if ($("div.ddl > span").text().contains("entreprise")){
if ($("input[name*='entreprise']").val() == "") {
$("input[name*='entreprise']").addClass("error");
bResult = false;
}else {
$("input[name*='entreprise']").removeClass("error");
}
} else if ($("div.ddl > span").text().contains("école")){
if ($("input[name*='ecole']").val() == "") {
$("input[name*='ecole']").addClass("error");
bResult = false;
}else {
$("input[name*='ecole']").removeClass("error");
}
}
return bResult;
}
Do you have any idea about what is wrong...?
Best regards
Audrey
EDIT : I changed my submit button; I put a with onclick which submits the form if bResut == true
Try registering your submit handler to the form using JS, so you can access the event and call preventDefault() instead of (or in addition to) returning false;
Like so:
document.getElementById('formContact').onsubmit = function(e) {
//your validateChamps stuff goes here
if(!bResult) e.preventDefault();
};
EDIT : I changed my submit button; I put a with onclick which submits the form if bResut == true

Javascript validation error

I have written the following code in html and the javascript file is also embedded below
<!DOCTYPE html>
<meta charset="utf-8">
<HTML>
<head>
<link rel="stylesheet" href="admin.css"/>
<script type="text/javascript" src="common.js"></script>
</head>
<BODY>
<div class="adminnav" id="adminnav">
<ul>
<li>Insert
<ul>
<li>Insert Course</li>
<li>Insert Student</li>
<li>Insert Teacher</li>
<li>Insert Subject</li>
</ul>
</li>
</ul>
</div>
<div class="addcourse" >
<form name="course" onSubmit='return validcourse()' method="POST">
Course Name:
<input type="text" name="coursename" id="cname" /><br>
Duration:<input type="text" name="cd"/>
<br>
Course Id:<input name="cid" type="text" /><br>
<input type="submit" value="submit" name="submit"><input type="reset" name="coursereset">
</form>
</div>
</BODY>
</HTML>
common.js
function validcourse()
{
var course_name=document.course.coursename;
var course_duration=document.course.cd;
var course_id=document.course.cid;
if(course_name_valid(course_name))
{
{
if(course_duration_valid(course_duration))
{
if(course_id_valid(cid))
{
}
}
}
}
}
function course_name_valid(course_name)
{
var letters=/^[A-Za-z]+$/;
if(course_name.value.match(letters))
{
return true;
}
else
{
alert("Course name must have alphabets only");
course_name.focus();
return false;
}
}
function course_duration_valid(course_duration)
{
var letters=/^[1-9]+$/;
if(cd.value.match(letters))
{
return true;
}
else
{
alert("Course Duration can have numbers only");
course_duration.focus();
retun false;
}
}
function course_id_valid(course_id)
{
var letters=/^[0-9a-zA-z]+$/;
if(course_id.value.match(letters))
{
return true;
}
else
{
alert('Course ID must have character and numeric values only');
course_id.focus();
return false;
}
}
My problem is that nothing is happening no error messages are given.
Error messages are given only for course name but not for course duration and course id?
Here is a link to jsfiddle http://jsfiddle.net/amolkarale/aTfq6/1/
You are not returning anything from validcourse. Add a return true; and return false; in there, to either let the submission continue or stop the submission from happening:
function validcourse()
{
var course_name=document.course.coursename;
var course_duration=document.course.cd;
var course_id=document.course.cid;
if(course_name_valid(course_name))
{
{
if(course_duration_valid(course_duration))
{
if(course_id_valid(cid))
{
return true;
}
}
}
}
return false;
}
Looks like you have a syntax error in your third functioncourse_duration_valid(course_duration)
retrun false;
should be:
return false;
Okay, so I got your stuff to work. Here are the changes needed:
First, object references need to be cleaner in your DOM
var course_name=document.getElementById("cname");
var course_duration=document.getElementById("cd");
var course_id=document.getElementById("cid");
As you can see, the elements need to have their individual ids.
Course Name:
<input type="text" name="coursename" id="cname" /><br>
Duration:
<input type="text" name="cd" id="cd"/><br>
Course Id:
<input name="cid" type="text" id="cid" /><br>
Finally, the retrun needed to be corrected, as already pointed out by #Steve

Categories