Checking blank field in text area - javascript

I have 3 text box and 1 textarea field.
id, name, address, contact.
All are java scripted in the purpose of checking blank field.
I did it in this way :
javascript code :
function checkForm()
{
var id=document.getElementById("id").value;
var name=document.getElementById("name").value;
var address=document.getElementById("address").value;
var contact=document.getElementById("contact").value;
if(id.length<1 )
{
alert("Please enter all the informations!");
return false;
}
if(name.length<1 )
{
alert("Please enter the name!");
return false;
}
if(address.length<1 )
{
alert("Please enter the address!");
return false;
}
if(contact.length<1 )
{
alert("Please enter the contact!");
return false;
}
html code :
<form method="post" action="clients.php" onSubmit="return checkForm()">
id <input type="text" name="id" id="id">
name <input type="text" name="name" id="name">
address <textarea name="address" id="address"> </textarea>
contact <input type="text" name="contact" id="contact">
<input type="submit" name="submit" value="Enter">
</form>
All are working except textarea. I am trying with some other code, founded in the internet, but those aren't working. Maintaining the serial (id then name then address then contact....) how can i check the blank space of the textarea?
Thanks a lot in advance.

Use trim function to remove whitespaces
var id=document.getElementById("id").value.trim();
var name=document.getElementById("name").value.trim();
var address=document.getElementById("address").value.trim();
var contact=document.getElementById("contact").value.trim();

Related

How to validate multiple fieldset in one form tag?

I am working on a form checking. I am stuck on how to stop submitting the form.
So basically, the form has 2 fieldsets (Creat New Customer and Return customer). I have a function which is checking the return customer fieldset if either one of the text field is blank then it will display an message. However, this function also affects on the fieldset (New customer), thus even all the text fields of new customer filled out, it display the message from that function as well. My code:
HTML
<form action="" onsubmit="return loginCheck()">
<fieldset>
<legend>
Create New Account
</legend>
<label>
Account:
<input name="ACCOUNT" size="16" type="text" id="acc"/>
</label>
<label>
Password:
<input name="PW" size="32" type="password" id="pw"/>
</label>
<label>
Password Again:
<input name="PW2" size="32" type="password" id="pw2"/>
</label>
<label>
Email:
<input name="EMAIL" size="32" type="text" id="email"/>
</label>
</fieldset>
<fieldset>
<legend>
Login
</legend>
<label>
Account:
<input name="ACCOUNT" size="16" type="text" id="loginAcc"/>
</label>
<label>
Password:
<input name="PW" size="32" type="password" id="loginPass"/>
</label>
</fieldset>
<input value="Submit" type="submit" id="submit"/>
<input value="Reset" type="reset" id="reset"/>
JS:
function loginCheck() {
var x = document.getElementById("loginAcc");
var y = document.getElementById("loginPass");
if (x.value == "") {
alert("You must type in both fields");
return false;
}
if (y.value == "") {
alert("You must type in both fields");
return false;
}
return true;
}
How can I fix to get that function just check the login fieldset without affect on the create new customer fieldset? Thank you!
You would have to check if the user is trying to enter a new account or his credentials, then check if the form is filled correctly...
function loginCheck() {
var a = document.getElementById("acc");
var b = document.getElementById("pwd");
var c = document.getElementById("pwd2");
var d = document.getElementById("email");
var x = document.getElementById("loginAcc");
var y = document.getElementById("loginPass");
if(a.value!="" || b.value!="" || c.value!="" || d.value!="" ||){
//Do logic to validate creation fieldset.
}else{
//Do logic to validate login
}
return true;
}
There might exist better solutions tough, you could have 2 forms instead of one or something in those lines... What the code above does is really simple, just checks if the user tries to create an account and then validates it. If the user types in his account name in the create form, and notices it is not the right place, then fills the login fields, the script will not work as expected by the user... Try to play with that a bit to find your best solution.

How to validate form input text with javascript

I'm trying to create a form with different inputs, input validation error receiving text, it does not validate (I want to be just text). The code is:
<form action="" id="myform" name="checkform" onsubmit="return validateform()" method="post">
<label for='Name'>Name:</label>
<input type="text" name="name" id="name"><br>
<label for='Surname'>Surname:</label>
<input type="text" name="surname" ><br>
<input type="submit" name="submit" value="Submit">
</form>
The javascript is:
function validateform(){
if(document.checkform.name.value == ""){
window.alert("Please insert your name.");
document.checkform.name.focus();
return false;
}
var nameText = document.forms["myform"]["name"].value; /* here is the problem :-( */
if (!name.match(/^\s*[A-Za-z]+\s*$/)) {
alert("Insert just letters !!!");
return false;
}
}
function validateform() {
var nameTxtBx = document.checkform.name,
name = nameTxtBx.value; //<-- added this line
if (name == "") {
alert("Please insert your name.");
nameTxtBx.focus();
return false;
}
if (!name.match(/^\s*[A-Za-z]+\s*$/)) {
alert("trebue doar litere");
return false;
}
return true; //<-- added this line
}
<form action="" id="myform" name="checkform" onsubmit="return validateform()" method="post">
<label for='Name'>Name:</label>
<input type="text" name="name" id="name">
<br>
<label for='Surname'>Surname:</label>
<input type="text" name="surname">
<br>
<input type="submit" name="submit" value="Submit">
</form>
You have typo in your variable, You just rename your variable nameText into name or vice versa.
var nameText = document.forms["myform"]["name"].value;
^^^^^^^
if (!name.match(/^\s*[A-Za-z]+\s*$/)) {
^^^^
Named form controls are made members of the form using their name. So even though the form has a name property, because your form also has a control with a name of name, then form.name references the control, not the form's name property.
Similarly, having a control with a name of submit means that you can't call the form's submit method, because form.submit references the control, not the method. So you should use control names that don't clash with standard form properties. Also, it's rare to require an ID for form controls since they can be referenced as properties of the form.
Lastly, it is handy to pass a reference to the form from the listener using this, then you don't need an ID on the form either. Consider:
<form onsubmit="return validateform(this)" ... >
Name: <input type="text" name="firstName"><br>
Surname: <input type="text" name="surname"><br>
<input type="submit" value="Submit">
</form>
Then in the function:
function validateform(form) {
Get the value of the firstName control once:
var firstName = form.firstName.value;
Now do the tests:
if (firstName == "") {
window.alert("Please insert your first name.");
form.firstName.focus();
return false;
}
It's more appropriate to use test than match if you want to test for a pattern rather than find all the matches:
if (!/^\s*[A-Za-z]+\s*$/.test(firstName)) {
alert("Insert just letters !!!");
return false;
}
}

Changing color of textbox and adding text on Javascript validation

So I'm trying to validate a form and I'm not being able to get the textbox change when the validation fails. Instead, the form gets completed. What I want is if the validation fails, the textbox border becomes color red and a text in red just below the textbox which says "Fill our this field!"
Here's what I have written just for the purpose of testing and it's not working and I'm not sure how to add the red=colored text just after the box concerned:
<form id="reg" method="POST" action="user.php" onsubmit="return validate()">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<button type="submit">Register</button>
</form>
function validate(){
var formIsValid = true;
if(first.value === ""){
//Not sure how to add Red-Colored Text below the box which says "Fill our this field!"
first.borderColor = "red"; //NOT WORKING
formIsValid = false;
}
return formIsValid;
}
I believe this is what you are looking for,
http://jsfiddle.net/F8H7Y/
<form name= "reg" id="reg" method="POST" action="user.php" onsubmit="return validate()">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<input type="submit">Register</button>
</form>
function validate(){
var formIsValid = true;
var first=document.forms["reg"]["first"];
if(first.value == null || first.value == ""){
first.style.borderColor = "red";
formIsValid = false;
}
return formIsValid;
}
Have a look on this post
I think for text, you can use empty lable to make a text appear just below the textbox which say "Fill this textbox" on validation failure.

Form Validation without Alerts

I was wondering if there's a way to validate the form without using alerts. Like usually you would see red text beside the input box if you typed in the wrong information or something. And I don't want to use Jquery. I've included a div for the red text messages in the html - namemsg, commentmsg, emailmsg.
So far I've only got the code with alerts.
JavaScript:
function validateUser()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<2 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
{
alert("Valid Input");
}
return true;
}
Html
<form name="myForm" method="post">
<label>*Name:</label>
<input type="text" name="name" title="Enter a your name" placeholder="Your Name" onclick="select()" required/>
<div id="namemsg"></div><br/>
<label>*E-mail:</label>
<input type="text" name="email" title="Enter a valid email address" placeholder="me#example.com" onclick="select()" required/>
<div id="emailmsg"> </div><br/>
<label>*Comment:</label>
<textarea name="comment" title="Enter your comments" placeholder="Enter your comments." onclick="select()" required/></textarea>
<div id="commentmsg"> </div>
<label id="error"> </label> <br/>
<input type="submit" value="Submit" onclick="return validateUser()">
</form>
You can place a span/label next to validated field with predefined text and style and display style of none. If validation detects an invalid input - change the display style to "" to make the label visible.
Update
I do see you have already predefined DIV. Define it as
<div id="emailmsg" style="color:Red;display:none">Not a valid e-mail address</div>
And in JavaScript instead of
alert("Not a valid e-mail address");
Use
document.getElementById("emailmsg").style.display=""
Instead of showing alert message box you can color that textbox borders to red color and show the error beneath it. Like, if you replace the following line of code:
alert("Not a valid e-mail address");
With:
document.forms["myForm"]["email"].style.border = "1px solid red";
document.getElementById("emailmsg").innerHTML = "Not a valid e-mail address";
The above code will highlight the borders of email field with red color and show error in emailmsg div.
Hope this can help.
your html:
<form name="myForm" method="post">
<label>*Name:</label>
<input type="text" name="name" title="Enter a your name" placeholder="Your Name" onclick="select()" required/>
<div id="namemsg"></div><br/>
<label>*E-mail:</label>
<input type="text" name="email" title="Enter a valid email address" placeholder="me#example.com" onclick="select()" required/>
// this span is hidden until you show it as error msg
<span id="error" style='display: none'>Not a valid e-mail address<span>
<div id="emailmsg"> </div><br/>
<label>*Comment:</label>
<textarea name="comment" title="Enter your comments" placeholder="Enter your comments." onclick="select()" required/></textarea>
<div id="commentmsg"> </div>
<label id="error"> </label> <br/>
<input type="submit" value="Submit" onclick="return validateUser()">
</form>
your js:
function validateUser()
{{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<2 || dotpos<atpos+2 || dotpos+2>=x.length)
{
//instead of alerting error show your error span try to put nice css for it
document.getElementById('error').style.display="block";
return false;
}
{alert("Valid Input");}
return true;
}
First, I would recommend attaching the execute of the function to the event OnSubmit.
HTML:
<form method="post" name="myForm" onsubmit="return validateUser(this);">
JS:
function validateUser(formObj) {}
Next, the only thing you need to do, is just have some sort of container, and if the function detects an error, just append the error text to it.
At the start of each function call, empty the container.
If you want the error to appear next to the textbox/any input tag, just add a div/span next to each field and append the error to it.
document.getElementById("emailmsg").innerHTML = "Not cool...";
This should help.
if (atpos<2 || dotpos<atpos+2 || dotpos+2>=x.length){
// validate message function call
valMessage('emailmsg', 'Not a valid e-mail address');
return false;
}
// validate message function
function valMessage(divName, content) {
document.getElementById(divName).innerHTML = content;
}

Form alerts for multipe inputs

I have the following code, and need to get an alert that will specify which fields are empty or null, and return an alert for each empty or null field. I'm new to JavaScript and struggling a great deal with this. Can anyone give me some advice on this?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function checkForm(form){
var len = form.length;
//create for loop
for (var i=0; i<len; i++){
if (form.elements[i].type=="text" || form.elements[i].type==null){
if (form.fax number.value=="" || form.fax number.type==null){
alert("Please fill out the fax number field");
}
}
}
}
function emailTest(emailText){
var email = emailText.value;
var emailPattern = /^.+#.+\..{2,}$/;
if (!(emailPattern.test(email))) {
alert("Please enter a valid email address.");
document.myForm[1].focus();
}
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<H3>Assignment 2 Form</H3>
<HR>
<FORM NAME="myForm" METHOD="post"
ACTION="mailto:joeschmoe#blahblah.ca">
Name:<BR>
<INPUT TYPE="text" size="30" NAME="name"><br>
Email address:<BR>
<INPUT TYPE="text" size="30" NAME="email address" onBlur="emailTest(this);"><br>
Phone number:<BR>
<INPUT TYPE="text" size="30" NAME="phone number"><br>
Fax number:<BR>
<INPUT TYPE="text" size="30" NAME="fax number"><p>
<INPUT TYPE="submit" VALUE="Submit Data" onClick="return checkForm(this.form);">
<INPUT TYPE="reset" VALUE="Reset Form">
</FORM>
</BODY>
</HTML>
Ok...wow. I spent way too much time on this.
Your form should look like the following:
<FORM NAME="myForm" id="myForm">
<label for="name">Name:</label><br />
<INPUT TYPE="text" size="30" NAME="name" /><br />
<label for="email_address">Email address:</label><BR />
<INPUT TYPE="text" size="30" NAME="email_address" /><br />
<label for="phone_number">Phone number:</label><BR />
<INPUT TYPE="text" size="30" NAME="phone_number" /><br />
<label for="fax_number">Fax number:</label><BR />
<INPUT TYPE="text" size="30" NAME="fax_number" /><br />
<INPUT TYPE="button" VALUE="Submit Data" onClick="return checkForm()" />
<INPUT TYPE="reset" VALUE="Reset Form" />
</FORM>
Form Summary:
You should utilize labels for form elements
Never use spaces for the name attribute or any identifying attribute for that matter (name, class, id)
inputs should end with /> as should any tag without an end tag (<br /> too)
I pulled out the onBlur event and just added it as a piece of the overall validation process. No need to make it too complicated
I used a button input type instead of a submit input type. See why in the JavaScript
And then your JavaScript:
function checkForm() {
var valid = false; //Set a boolean variable that will be changed on each block
//of validation
if (document.myForm.fax_number.value === "") {
alert("Please fill out the fax number field");
}
if (document.myForm.email_address.value === "") {
alert("Email address is required");
} else {
valid = emailTest(document.myForm.email_address.value);
}
//all other checks within if statements
if (valid) {
document.myForm.action = "mailto:soandso#so.com";
document.myForm.submit();
}
}
function emailTest(emailText) {
var emailPattern = /^.+#.+\..{2,}$/;
var ret = false;
if (!(emailPattern.test(emailText))) {
alert("Please enter a valid email address.");
} else {
ret = true;
}
return ret;
}
Javascript Summary
In JavaScript interacting with HTML forms, forms are called as such: document.formName where formName is the string in the name="" attribute of the form tag or document.forms[i] where i is the numerical instance of the form on the page, i.e. the first form on the page is i = 0, thus it would be called as document.forms[0]
Check each input by name for a value with document.myForm.(elementName).value where elementName is the string from your <input>s name attribute.
Instead of using a submit, I used a regular button. When the "Submit Data" button is clicked in the form, it runs checkForm() which makes sure everything is valid
If everything is valid, it assigns an action to the form with document.myForm.action=youraction and then submits it via JavaScript with document.myForm.submit()
Notes
Don't use W3Schools to learn about anything ever.
Read more about forms here

Categories

Resources