How to get my validated JavaScript data into a MySQL database - javascript

To my understanding since JavaScript is a browser-side language and MySQL is server side, I need a server-side language that can interact with the browser such as PHP. I've been looking for solutions here and on the web but to no luck.
My question is -- with the code below is there general format on how can send validated information through the PHP to get to a database?
HTML:
<form method="post" name="regForm" onSubmit="return validateRegForm();">
<table align="center" border="1" bordercolor="black" bgcolor="white" cellpadding="5" cellspacing="0" width="50%">
<tr>
<td>
<table align="center" bordercolor="white" border="0" cellpadding="5" cellspacing="0">
<tr>
<td align="center" colspan="2"><strong>Registration</strong></b></td>
</tr>
<tr>
<td colspan="2"><br></td>
</tr>
<tr>
<td align="right" width="20%">E-mail:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="email" maxlength="50" size="30" placeholder=" email"></td>
</tr>
<tr>
<td align="right" width="20%">Username:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="username" maxlength="50" size="30" placeholder=" username"></td>
</tr>
<tr>
<td align="right" width="20%">Password:</td>
<td align="left" width="30%"><input class="largeTextBox" type="password" name="password" maxlength="50" size="30" placeholder=" password"></td>
</tr>
<tr>
<td align="right" width="20%">Confirm Password:</td>
<td align="left" width="30%"><input class="largeTextBox" type="password" name="cpassword" maxlength="50" size="30" placeholder=" confirm password"></td>
</tr>
<tr>
<td align="right" width="20%">First Name:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="firstname" maxlength="50" size="30" placeholder=" first name"></td>
</tr>
<tr>
<td align="right" width="20%">Last Name:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="lastname" maxlength="50" size="30" placeholder=" last name"></td>
</tr>
<tr>
<td align="right" width="20%">Team Name:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="teamname" maxlength="50" size="30" placeholder=" team name"></td>
</tr>
<tr>
<td colspan="2" align="center"><input class="bigButton" type="submit" value="Register"></td>
</tr>
</table>
</td>
</tr>
</table>
</form>
JavaScript:
function validateRegForm()
{
//Validates email address
var a = document.forms["regForm"]["email"].value;
if (a == null || a == "") {
alert("You forgot to enter your Email!");
return false;
} else {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (a.match(mailformat)) {
document.regForm.email.focus();
} else {
alert("You have entered an invalid Email Address!");
document.regForm.email.focus();
return false;
}
}
//Validates username
var aa = document.forms["regForm"]["username"].value;
if (aa == null || aa == "") {
alert("You forgot to enter your Username!");
document.regForm.username.focus();
return false;
}
re = /^\w+$/;
if (!re.test(regForm.username.value)) {
alert("Your Username must contain only letters, numbers, and underscores!");
document.regForm.username.focus();
return false;
}
if (aa.length < 7) {
alert("Your Username is too short! (8 character min)");
document.regForm.username.focus();
return false;
}
//Validates password & confirm password
if (regForm.password.value != "" && regForm.password.value == regForm.cpassword.value) {
if (regForm.password.value.length < 7) {
alert("Your Password must contain at least 8 characters!");
document.regForm.email.focus();
return false;
}
re = /[0-9]/;
if(!re.test(regForm.password.value)) {
alert("Your Password must contain at least one number (0-9)!");
document.regForm.password.focus();
return false;
}
re = /[a-z]/;
if(!re.test(regForm.password.value)) {
alert("Your Password must contain at least one lowercase letter (a-z)!");
document.regForm.password.focus();
return false;
}
re = /[A-Z]/;
if(!re.test(regForm.password.value)) {
alert("Your Password must contain at least one uppercase letter (A-Z)!");
document.regForm.password.focus();
return false; }
} else {
alert("Please check that you've entered or confirmed your password!");
document.regForm.password.focus();
return false;
}
//Validates first name
var b = document.forms["regForm"]["firstname"].value;
if (b == null || b == "") {
alert('You forgot to enter your First Name!');
return false;
}
//Validates last name
var c = document.forms["regForm"]["lastname"].value;
if (c == null || c == "") {
alert('You forgot to enter your Last Name!');
return false;
}
//Validates team name
var d = document.forms["regForm"]["teamname"].value;
if (d == null || d == "") {
alert('You forgot to enter your Team Name!');
document.regForm.teamname.focus();
return false;
}
re = /^\w+$/;
if (!re.test(regForm.teamname.value)) {
alert("Team Name must contain only letters, numbers, and underscores!");
document.regForm.teamname.focus();
return false;
}
if (d.length < 7) {
alert("Your Team Name is too short! (8 character min)");
document.regForm.teamname.focus();
return false;
}
return true;
}

There are a lot of approaches to your problem.
This one is what I think,
<form method="post" name="regForm" onSubmit="return validateRegForm();">
This part should have an 'action'.
On your form, there should be an
<input type="submit" name="submit" value="Submit"/>
This will invoke that "onSubmit" action in your "form" tag.
Try this out. Maybe these are the things you're missing out.
Cheers!

Client-side validation has a different role than that of the server. While the server's job is to keep out bad guys and make sure your data is clean, client-side validation should have the purpose of making the filling out of forms as least annoying as possible.
Doing good server-side validation is a science in itself. Fortunately, there are frameworks that make it easier to do it properly (Laravel and CodeIgniter are personal favorites), but if you have the commendable aim of learning to do it from scratch, there's plenty out there to read.
Good client-side validation takes advantage of JavaScript's strengths. It's instant and shows the user exactly where the problem is. You've got that down for the most part, except for the fact that the user gets one error at a time and has to click through alerts until they've got it right. There's also some repetition we can get rid of.
We can gather your validation into an array of objects with a name and a regular expression.
var validators = [
{name: 'username', test: /^[\d\w]{8,}$/},
{name: 'email', test: /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/},
{name: 'password', test: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/},
{name: 'cpassword', test: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/},
{name: 'firstname', test: /w+/},
{name: 'lastname', test: /w+/},
{name: 'teamname', test: /[\w+\d+]{8,}/}
];
Next, let's get rid of the alerts and put red error messages right next to their fields. First, the CSS for that:
td.hide{
display: none;
}
td.error {
font-size: .8em;
color: #F00;
padding: 0 0 0 30%;
}
...and in our table, we'll add hidden rows with the error messages already in them, like so. You could get sophisticated and taylor the message to the type of error by modifying the validators array above with custom messages and then coding for it below, but for simplicity I'm going to leave it as one regex per field and hardcode the error into the hidden validation rows. You could also add ajax calls to the server checking whether usernames/emails are already taken, but this should be a good start.
Now we can make one function that iterates through the array whenever the user changes something. This doesn't cost a whole lot and is practically instant.
function validateRegForm(event)
{
var formIsValid = true;
for(var i=0; i < validators.length; i++){
var currentField = document.getElementsByName(validators[i].name)[0];
var validationField = document.getElementById(validators[i].name + "Validation");
//check that this field is valid, as well as the other filled out ones along the way
if(validators[i].name == event.target.name || currentField.value.length > 0){
if(validators[i].test.test(currentField.value)){
validationField.setAttribute("class", "hide");
}else{
validationField.setAttribute("class", "error");
formIsValid = false;
}
//do the passwords match?
if(currentField.name == 'cpassword' || validators[i].name == 'cpassword'){
if(document.getElementsByName('cpassword')[0].value != document.getElementsByName('password')[0].value){
document.getElementById('cpasswordValidation').setAttribute("class", "error");
formIsValid = false;
}
else {
document.getElementById('cpasswordValidation').setAttribute("class", "hide");
}
}
}
}
if(!formIsValid){
event.preventDefault();
}
return formIsValid;
}
Going over the script, we are first assuming the form is valid with var formIsValid. As soon as we hit something that isn't, we change it to false so that at the end, the form doesn't submit. Then we just iterate through and see what's valid. We ignore empty fields unless it's the one the user just changed, so that the user doesn't start with their email and then get red everywhere because it's all blank. Finally, we put in a special condition to compare passwords.
See my Codepen to see it in action.
On the server, you should check for the same things as above and then properly escape & encode it for storage in the database. You should not assume that the form was posted from your registration page. There are ways to check that on the server and reject the user if the request didn't come from your page. Most server-side languages have built-in ways to do this stuff, but a good framework will make it less of a headache.

Related

Button can't be enabled

My button can't be enabled after having 2 inputs in my textbox not sure how to do this. My button is <input id="rand" type="submit" value="submit" disabled> . I think that its because of the disabled that my entire function is not working... but I don't know any other way to enable it
<script>
function validate()
{
var values = document.getElementById("digit").value;
if(values<0)
{
document.getElementById("numbers").innerHTML = "This is not a number, number must be greater or equal to zero"
return false
}
else if (!(typeof +values && values >= 0)|| values.trim() == "")
{
document.getElementById("numbers").innerHTML = "Fill in a number";
return false;
}
else if (values>=0)
{
document.getElementById("numbers").innerHTML = "";
}
var values1 = document.getElementById("digit1").value;
if(values1<0)
{
document.getElementById("numbers1").innerHTML = "This is not a number, number must be greater or equal to zero"
return false
}
else if (!(typeof +values1 && values1 >= 0)|| values1.trim() == "")
{
document.getElementById("numbers1").innerHTML = "Fill in a number";
return false;
}
else if (values >= values1)
{
document.getElementById("numbers1").innerHTML = "Highest number is smaller than lowest number";
return false;
}
else if (values1 > values)
{
document.getElementById("numbers1").innerHTML = "";
}
if((document.getElementById("digit").value>0) && (document.getElementById("digit1").value>0))
{
document.getElementById("rand").removeAttribute('disabled');
}
else
{
document.getElementById("rand").setAttribute('disabled', 'disabled');
}
}
</script>
This is my codes from my
<body>
<table style="border-collapse: collapse" width="100%">
<form action="random" method="get" onSubmit="return validate()">
<tr>
<td>
Lowest number:
<input id="digit" type="text" name="lowestnumber">
<span id="numbers"></span>
<br/>
</td>
</tr>
<tr>
<td>
Highest number:
<input id="digit1" type="text" name="highestnumber">
<span id="numbers1"></span>
</td>
</tr>
<tr>
<td>
<input id="rand" type="submit" value="submit" disabled><br/>
<input id="randno" type="text"><br/>
</td>
</tr>
<tr>
<td>
<input id="guess" type="text"><br/>
<input id="guessbut" type="button" value="" >
</td>
</tr>
<br/>
</form>
</table>
</body>
You're enabling the button the right way, by using removeAttribute('disabled'). Maybe you just made some logic error, so you don't reach the removeAttribute statement. Check it out by using console.log()
I think everything works well, except one "u never call your javascript!!".
your js code is wrapped in validate() function and u never call it so it wont be ran forever.
u can try call it using
onchange="validate()"
in your input
so this what it will look like
<tr>
<td>
Lowest number:
<input id="digit" type="text" name="lowestnumber" onchange="validate()">
<span id="numbers"></span>
<br/>
</td>
</tr>
<tr>
<td>
Highest number:
<input id="digit1" type="text" name="highestnumber" onchange="validate()">
<span id="numbers1"></span>
</td>
</tr>
I am not an experienced coder but from what I am reading here is that you are trying to validate an input form and based on that you then disable/enable an input field.
First it is best when validating an input form using regex validations instead of conditionals. Then as soon as the regex is true then you would have to parseInt() which converts the input string to a number (since all inputs are type of string). Then you can make the comparisons.
I've broken down the validations in three stages for you to understand, I know it is a bit messy code but everything depends on the implementation. First validation checks the input with a regex then the second validation checks if the number with the first field and the third validation checks if there is any message/text. If there is no text then all is good so the Rad input field is enabled.
function firstValidation(valueToTest) {
// Your regex matches positive numbers only
var yourRegex = /^[+]?\d+([.]\d+)?$/;
// Test the regex, if false then return the message
return yourRegex.test(valueToTest) ?
"" :
"<br/>Input a number, the number must be greater or equal to zero";
}
function secondValidation(firstInput, secondInput) {
return parseInt(firstInput) < parseInt(secondInput) ?
"<br>Highest number is smaller than lowest number" :
"";
}
function thirdValidation() {
var randField = document.getElementById("rand");
var highestMessage = document.getElementById("message-highestnumber")
.innerHTML;
var lowestMessage = document.getElementById("message-lowestnumber").innerHTML;
// If highestMessage or LowestMessage have no message then everything is ok
randField.disabled = highestMessage || lowestMessage;
}
function validate(inputField) {
var message = firstValidation(inputField.value);
var lowestNumber = document.getElementById("lowestnumber");
var highestNumber = document.getElementById("highestnumber");
// Is the Input field the highest number? Then make the extra check
if (inputField === highestNumber)
message += secondValidation(highestNumber.value, lowestNumber.value);
// After all the checks display the message nextElementSibling will automatically go to the next element which is a span
inputField.nextElementSibling.innerHTML = message;
thirdValidation();
}
<body>
<table>
<tr>
<td>
Lowest number:
<input id="lowestnumber" type="text" name="lowestnumber" onchange="validate(this)">
<span id="message-lowestnumber"></span>
</tr>
</td>
<tr>
<td>
Highest number:
<input id="highestnumber" type="text" name="highestnumber" onchange="validate(this)">
<span id="message-highestnumber"></span>
</td>
</tr>
<tr>
<td>
Rand
<input id="rand" type="text" name="rand"><br />
<span id="message-rand"></span></td>
</tr>
</table>
</body>
Again I might complicate things but everything is based on what implementation you do.

Javascript: validating form fields by regular expression and using if/else statement

In my program I have created form and fields in form. I am trying to validate fields. For that I have used regular expression though my regular expression is correct but regular expression for phone doesn't execute. Can anyone tell me wether I defined if/else statement for validation correctly ?
code:
function validateForm() {
var zip = document.myform.zip;
var email = document.myform.email;
var phone = document.myform.phone;
if (email.value == "") {
window.alert("Please enter email Address.");
state.focus();
return false;
}
var regEx2 = /^[0-9]{5}(?:-[0-9]{4})?$/;
if (zip.value.match(regEx2)) {
return true;
} else {
window.alert("Please provide a zip in the ##### or #####-#### format.");
zip.focus();
return false;
}
var regEx = /^(?:\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}$/;
if (phone.value.match(regEx)) {
return true;
} else {
window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");
phone.focus();
return false;
}
}
<form name="myform" id="myform" action="" onsubmit="return validateForm()" method="post">
<table cellspacing="2" cellpadding="2" border="0">
<tr>
<td align="right">Zip</td>
<td><input type="text" name="zip" maxlength="15" size="28" /></td>
</tr>
<tr>
<td align="right">Telephone number</td>
<td><input type="text" name="phone" size="28" placeholder="(555) 555-5555" /></td>
</tr>
<tr>
<td align="right"> EMail </td>
<td> <input type="text" name="email" size="28" /></td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /> </td>
</tr>
</table>
The problem is here -
if (zip.value.match(regEx2)) {
return true;
} else {
window.alert("Please provide a zip in the ##### or #####-#### format.");
zip.focus();
return false;
}
You are returning from this point regardless of valid or invalid zip. Code blocks afterward won't get executed.
I would suggest not to return in every successful if block, because, the code execution will return from that point without validating the other fields.
function validateForm() {
var valid = true;
var zip = document.myform.zip;
var email = document.myform.email;
var phone = document.myform.phone;
if (email.value == "")
{
window.alert("Please enter email Address.");
email.focus();
valid = false;
}
var regEx2 = \^[0-9]{5}(?:-[0-9]{4})?$\;
if(!zip.value.match(regEx2))
{
window.alert( "Please provide a zip in the ##### or #####-#### format." );
zip.focus() ;
valid = false;
}
var regEx = \^(?:\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}$\;
if(!phone.value.match(regEx))
{
window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");
phone.focus();
valid = false;
}
return valid;
}
if you really want to validate one field only when all the previous fields are valid (as your current code), this is working -
function validateForm() {
var zip = document.myform.zip;
var email = document.myform.email;
var phone = document.myform.phone;
if (email.value == "")
{
window.alert("Please enter email Address.");
email.focus();
return false;
}
var regEx2 = \^[0-9]{5}(?:-[0-9]{4})?$\;
if(!zip.value.match(regEx2))
{
window.alert( "Please provide a zip in the ##### or #####-#### format." );
zip.focus() ;
return false;
}
var regEx = \^(?:\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}$\;
if(!phone.value.match(regEx))
{
window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");
phone.focus();
return false;
}
return true;
}
Here is the complete script -
<!DOCTYPE html>
<html>
<head>
<title>NumerValidation</title>
</head>
<body>
<form name="myform" id="myform" action="" onsubmit="return validateForm();" method="post">
<table cellspacing="2" cellpadding="2" border="0">
<tr>
<td align="right">Zip</td>
<td><input type="text" name="zip" maxlength="15" size="28"/></td>
</tr>
<tr>
<td align="right">Telephone number</td>
<td><input type="text" name="phone" size="28" placeholder="(555) 555-5555"/></td>
</tr>
<tr>
<td align="right"> EMail </td>
<td> <input type="text" name="email" size="28" /></td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit"/> </td>
</tr>
</table>
</form>
<script>
function validateForm() {
var zip = document.myform.zip;
var email = document.myform.email;
var phone = document.myform.phone;
if (email.value == "")
{
window.alert("Please enter email Address.");
email.focus();
return false;
}
var regEx2 = /^[0-9]{5}(?:-[0-9]{4})?$/;
if(!zip.value.match(regEx2))
{
window.alert( "Please provide a zip in the ##### or #####-#### format." );
zip.focus() ;
return false;
}
var regEx = /^(?:\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}$/;
if(!phone.value.match(regEx))
{
window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");
phone.focus();
return false;
}
return true;
}
</script>
</body>
</html>

Javascript to prevent form post if not validated

I have the following validation code for a simple form. I am able to perform basic validation but the form still gets posted even if the data is wrong and an alert is generated. How can I stop that from happening?
JS CODE
function validate(){
validateForm();
}
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["pname"].value;
var email = document.forms["myForm"]["email"].value;
var phone = document.forms["myForm"]["phone"].value;
var date = document.forms["myForm"]["date"].value;
var month = document.forms["myForm"]["month"].value;
var year = document.forms["myForm"]["year"].value;
window.load = function() {
var myForm = document.getElementById('myForm');
myForm.onsubmit = function(e) {
return validateForm(); // will be false if the form is invalid
}
}
if (x == null || x == "") {
alert("Name must be filled out");
return false;}
else if (y == null || y == "") {
alert("Address must be filled out");
return false;
}
else if(email == '' || email.indexOf('#') == -1 || email.indexOf('.') == -1)
{
alert("Insert Valid Email Address");
return false;
}
else if(phone == ''|| phone <1000000000 || phone >9999999999){
alert("Enter valid phone number");
return false;
}else if(date =='' || date<01 || date >31){
alert("Enter valid date ");
return false;
}else if(month =='' || month<1 || month >12){
alert("Enter valid month ");
return false;
}else if(year =='' || year<1800 || year >2015){
alert("Enter valid year ");
return false;
}
}
Form
<form name="myForm" action="http://www.randyconnolly.com/tests/process.php" onsubmit="return validate()" method="post">
<table width="30%" border="0" align="center" cellpadding="10" cellspacing="20">
<tr>
<td width="20%"> <span style="font-size: 22px">Name:</span><br>
<br /></td>
<td width="80%"><input type="text" name="fname" required /></td>
</tr>
<tr>
<td><span style="font-size: 22px">Picture Name: <br>
<br></span></td>
<td><input type="text" name="pname" required /></td>
</tr>
<tr>
<td><span style="font-size: 22px">Email:</span> <br>
<br></td>
<td><input type="text" name="email" required /></td>
</tr>
<tr>
<td><span style="font-size: 22px">Phone:</span> <br>
<br></td>
<td><input type="number" name="phone" required /></td>
</tr>
<tr>
<td><span style="font-size: 22px">Date(mm/dd/yyyy):</span></td>
<td><input type="text" name="month" size="2" required />
/
<input type="text" name="date" size="2" required />
/
<input type="text" name="year" size="4" required /></td>
</tr>
<tr>
<td><span style="font-size: 22px">Artwork</span></td>
<td><input type="file" accept="image/gif" name="pic" ></td>
</tr>
</table>
<br><br>
<input class="button-0" type="submit" value="Submit" />
<br>
</form>
You have several issues with your code.
Your validation function needs to return false to prevent the form submission.
You are registering the window.onload handler inside of the validateForm function. Since, the the time the validateForm function is called, the form is already being submitted.
The handler in your markup is validate. Your validate method doesn't return anything so submission won't be prevented by that either.
The easiest way to fix everything would to be to remove the window.onload handler from your code altogether. You could then change validate to:
function validate() {
return validateForm();
}
And submission should be prevented properly.
I got it working. Instead of calling validate() and in that calling validateForm() I directly called validateForm() at the onsubmit. Thanks for the help.

How would i validate a text field in html using javascript?

I have a text field for a user to enter and examination number which is 4 digits long. How would I validate the text field to make sure the digits entered are exactly 4 digits (including a leading 0).
So far I have validated it so that it isn't left blank.
Here's my Javascript:
function validateForm()
{
var result = true;
var msg="";
if (document.ExamEntry.name.value=="")
{
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="")
{
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if (document.ExamEntry.ExamNo.value=="")
{
msg+="You must enter your Examination number \n";
document.ExamEntry.ExamNo.focus();
document.getElementById('ExamNo').style.color="red";
result = false;
}
if(msg=="")
{
return result;
}
{
alert(msg)
return result;
}
}
Here's My html :
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
</tr>
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject"/></td>
</tr>
<tr>
<td id="ExamNo">Examination number</td>
<td><input type="text" name="ExamNo"/></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onClick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
/^\d\d\d\d$/.test(document.ExamEntry.ExamNo.value)
It returns a boolean that check if ExamNo matches that regular expression (4-digit string).
Complete example:
if (!/^\d\d\d\d$/.test(document.ExamEntry.ExamNo.value))
{
msg+="Examination number should be 4-digit number. \n";
document.ExamEntry.ExamNo.focus();
document.getElementById('ExamNo').style.color="red";
result = false;
}
Please see the below link
http://jqueryvalidation.org/documentation/
http://jqueryvalidation.org/files/demo/
This is a validation plugin and easy to use.

Are there any very Simple JQuery Validation?

Hi I'm looking to add some simple validation to a form.
There are 2 textboxes which the user is expected to enter only numbers and it must be greater than zero. The jquery code is in it's own file (the form consists of html / jquery / php). The first number is for 'previous age' and the second number is for 'current age'. For example, if the user enters '0' in either textbox, an alert or message box should appear informing them that they need to enter a number greater than zero. Anything other than a number greater than zero entered into the textbox should result in the alert message.
As a side note, the .php file is used only for the calculation/math once the user has cleared the requirements of the form.
If someone could provide a clear and concise example, it would much appreciated. I've tried to find a suitable example via google searching, however nothing seemed to fit. Also I'm trying to avoid using a validator plugin, which seemed to be the go to answer when googling the question.
I have my reasons and will be more than happy to explain if needed.
Thank-you,
Charles
if you take away the aspect of your question, validation is fairly basic. All jquery would be used for is to make selecting specific dom elements easier
$(function() {
$('form').submit(function() {
return checkFormIsValid();
});
$('#field1').keyup(function() {
checkField(this.id);
});
$('#field2').keyup(function() {
checkField(this.id);
});
});
function checkFormIsValid()
{
return checkField('field1') && checkField('field2');
}
function checkField(fieldId)
{
var val = $('#'+fieldId).val();
// validation logic
if(isValid) {
return true;
} else {
alert(fieldId+ ' is not valid');
return false;
}
}
This basic validation will be triggered on each field, as well as when the user submits the form.
As Ben Rowe suggest you can use that code, but in checkField(fieldId) function you have to validate that input data should be integer only in that case you can use these codes to vaildate that.
Regex to validet input data
var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function isEmail(s) {
return String(s).search(isEmail_re) != -1;
}
function isBlank(s) {
if (!s || s.length == 0) {
return true;
}
// checks for a non-white space character
// which I think [citation needed] is faster
// than removing all the whitespace and checking
// against an empty string
return !/[^\s]+/.test(s);
}
function SendContactForm() {
var isFormValid = true;
var isEmailOk = isEmail($('#cemail').val());
if (isEmailOk == false) {
$('#emEmail').css('color', 'red');
isFormValid = false;
}
else {
$('#emEmail').css('color', 'black');
}
var isNameOk = isBlank($('#cname').val());
if (isNameOk) {
$('#emName').css('color', 'red');
isFormValid = false;
//alert('!');
}
else {
$('#emName').css('color', 'black');
}
var isSubjectOk = isBlank($('#csubject').val());
if (isSubjectOk) {
$('#emSubject').css('color', 'red');
isFormValid = false;
}
else {
$('#emSubject').css('color', 'black');
}
var isMesageOk = isBlank($('#cmessage').val());
if (isMesageOk) {
$('#emMessage').css('color', 'red');
isFormValid = false;
}
else {
$('#emMessage').css('color', 'black');
}
if (isFormValid) {
$('#contactFormFields').hide("explode", 1000);
$.post("/Home/SendContactForm", { email: $('#cemail').val(),
name: $('#cname').val(),
subject: $('#csubject').val(),
message: $('#cmessage').val()
},
function (data) {
if (data.length > 0) {
// alert(data);
}
});
}
}
<div id="contactFormFields">
<table>
<tr>
<td style="width: 150px;">
E-Mail
</td>
<td>
<input id="cemail" type="text" value="E-mail" name="email" size="25" class="required email" /><em id="emEmail">*</em>
</td>
</tr>
<tr>
<td style="width: 150px;">
Name
</td>
<td>
<input id="cname" name="name" size="25" class="required" maxlength="100" /><em id="emName">*</em>
</td>
</tr>
<tr>
<td style="width: 150px;">
Subject
</td>
<td>
<input id="csubject" name="subject" size="25" class="required" maxlength="200" /><em id="emSubject">*</em>
</td>
</tr>
<tr>
<td style="width: 150px; vertical-align: top;">
Message
</td>
<td>
<textarea id="cmessage" maxlength="1000" name="comment" cols="27" rows="10" class="required"></textarea><em id="emMessage">*</em>
</td>
</tr>
<tr>
<td style="width: 150px;">
</td>
<td>
<input type="submit" value="Send" class="input-btn" onclick="SendContactForm();" style=" width:100px; color: Black;" />
</td>
</tr>
</table>
</div>
maybe your looking for a plug in to validate form fields?
you can give this a try: http://www.vanadiumjs.com/
just add its js file and your ready.
adding a required validation is as simple as adding css like this
<input class=":required" type="text">
to add an integer validation
<input class=":integer" type="text">
and so on. just follow the link for more info.

Categories

Resources