Button can't be enabled - javascript

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.

Related

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.

Radio button validation (alert box) confirmation and rejection

I'm working on a HTML document which is an exam submission form. I've completed almost all of the set tasks however, I'm having trouble validating radio buttons. I've searched on stackoverflow however, the answers do not meet the criteria of the question. My completed code is shown below.
I'm having trouble with the bold part of this task:
Add a set of radio buttons to the form to accept a level of entry such as GCSE, AS or A2. Write a function that displays the level of entry to the user in an alert box so that the level can be confirmed or rejected.
Below is the code working, excluding the validation of the radio buttons. Seperatley, I have the code which doesn't work when implemented into the function validateForm().
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/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('examinationno').style.color = "red";
result = false;
}
if (document.ExamEntry.examno.value.length!== 4) {
msg+="Your Examination Number should be 4 digits.\n";
document.ExamEntry.examno.focus();
document.getElementById('examinationno').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<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="examinationno">Examination Number</td>
<td>
<input type="text" name="examno" />
</td>
</tr>
<tr>
<td>
<input type="radio" name="examtype" value="GCSE" />GCSE</td>
</tr>
<tr>
<td>
<input type="radio" name="examtype" value="AS" />AS</td>
</tr>
<tr>
<td>
<input type="radio" name="examtype" value="A2" />A2</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>
Based on the current code, why won't the following validate when added into the function?:
if(document.getElementById('GCSE').checked)
{examtype = "GCSE";
}
if(document.getElementById('AS').checked)
{examtype = "AS";
}
if(document.getElementById('A2').checked)
{examtype = "A2";
}
if(confirm("You have selected"+examtype+.Continue?")){
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
else{
alert("Action cancelled");
return false;
}
// Retrieving the checked radio button value
function getRadioValue (frmName, rbGroupName)
{
var radios = document[frmName].elements[rbGroupName];
for (var i=0; i <radios.length; i++)
{
if (radios[i].checked)
{
return radios[i].value;
}
}
return false;
}
Call the getRadioValue() inside validateForm()
// examtype gets false or GCSE or AS or A2
var examtype = getRadioValue ("ExamEntry", "examtype");
"Continue" is a keyword. So you have to wrap it in apostrophes("). I could not get the structure of if-statements, I made some changes. I hope this is what you are looking for..
if(confirm("You have selected"+examtype+". Continue?")){
if(msg==""){
alert(msg);
return result;
}
else{
alert("Action cancelled");
return false;
}
}

How to get my validated JavaScript data into a MySQL database

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.

I wish to make my code validate a field to make sure it is a number of four digits. How can I do this?

I am currently doing a GCSE course which allows me to ask for assistance from IT sources as long as I reference them in my investigation. I wish to make the following code validate that there is a number of four digits in the Examination Number entry field. I'm okay with simple validation but this is another step for me.
<head>
<title>Exam entry</title>
<script language="javascript" type="text/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.examnumber.value=="") {
msg+="You must enter your Examination Number \n";
document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color="red";
result = false;
}
var checked = null;
var inputs = document.getElementsByName('examtype');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
document.getElementById('examtype').style.color="red";
}
}
if(checked==null)
{
msg+="Please choose an option";
result = false;
}
else{
confirm("You have chosen "+checked.value+" is this the correct course?");
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examnumber">Examination Number</td>
<td><input type="text" name="examnumber" /></td>
</tr>
<tr>
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
</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>
</body>
Regarding checking if it is number, you can use some regex:
e.g.
var reg = /^\d{4}$/ig;
var regExRes = reg.exec(document.ExamEntry.examnumber.value);
if (document.ExamEntry.examnumber.value == "" || (regExRes == null || regExRes.length == 0)) {
msg += "You must enter your Examination Number \n";
document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color = "red";
result = false;
}
To avoid entering anything beside number, I would suggest you to use something like jquery pluging called masked input
EDIT:
line changed from var reg = /\d{4}/ig; to var reg = /^\d{4}$/ig;

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