Form Validation with JavaScript

Because data from HTML forms to be sent to a PHP file is preferable to do a check to see if they correspond to fields that have been introduced. De exemplu atunci cand un utilizator trimite un comentariu si a lasat goala o casuta sau a scris adresa de email aiurea sa putem opri trimiterea datelor mai departe. For example when a user sends a comment and left empty a box or writing email elsewhere we can stop sending further data.

For such verification can be used and PHP but I think that lasts longer. Javascript face fata cu succes acestei sarcini si codul este si foarte simplu. Javascript successfully handle this task and the code is very simple. Va arat in continuare cum poate Javascript sa interactioneze cu tastatura utilizatorului, putand in acest fel sa controleze tipul datelor introduse, fara sa permita introducerea altui tip de caractere. We further show how to interact with Javascript keyboard user can thus control the type of data entered, without allowing the introduction of another type of character. Asta este o actiune care nu poate fi facuta in PHP. This is an action that can not be done in PHP.

To find out which key was pressed and act according to this first must know which are orders that:

onkeypress when a key is pressed
onkeyup when a key is released
onkeydown when you press a key

To make the connection between an object and pressing the page html code can be used both inside the car and call the object html javascript functions:

<form>
<input type="text" value="apasa o tasta aici" onkeypress="alert('ai apasat o tasta in interiorul campului')" />
</form>
<script type="text/javascript">
function alertare () {
alert("You pressed a button inside html document")
} document.onkeypress=alertare();
</script>

 

Of course the above examples may be useful to validate forms nothing but help to better understand what lies ahead. Pentru a face validarea formularelor trebuie sa determinam ce tasta a fost apasata in interiorul obiectului respectiv. To validate forms must determine which key was pressed within the article.

For this it uses ASCII code to indicate key presses. Puteti sa vedeti aceste coduri in exemplul de mai jos. You can see these codes in the example below.

<script type="text/javascript">
function aratacod(e){
var unicode=e.keyCode? e.keyCode : e.charCode
alert("codul tastei este:" + unicode)
}
</script>
<form>
<input type="text" size="2" maxlength="1" onkeyup="aratacod(event); this.select()" />
</form>

This information is sufficient to give now some examples that can be used in real applications

Validation review based on the number of characters

<script type="text/javascript">

 

function limitarelungime(obj, length){
var lungime=length
if (obj.value.length>lungime)
obj.value=obj.value.substring(0, lungime)
} </script> Introduceti textul aici (lungimea maxima e de 20 de caractere):
<form>
<textarea onkeyup="return limitarelungime(this, 20)" style="width:300px;height:40px"></textarea> </form>

Phone number validation

We do this using our validation of the above. Vom limita numarul maxim de caractere la 10 si nu vom permite decat apasarea tastelor de la 0 la 9. We limit the maximum number of characters to 10 and will not allow just pressing keys 0 to 9. Pentru a impune aceasta restrictie ne vom folosi de codurile caracterelor. To impose this restriction we use the character codes.

<script type="text/javascript">
function numere(e){
var unicode=e.charCode? e.charCode : e.keyCode
if (unicode!=8){ //daca tasta apasata nu e backspace
if (unicode<48||unicode>57) //si nu e nici numar return false //nu se poate apasa
}
}
function limitarelungime(obj, length){
var lungime=length
if (obj.value.length>lungime)
obj.value=obj.value.substring(0, lungime)
}

 

</script> Enter your phone number (maximum length is 10 characters):
<form>
<textarea onkeypress="return numere(event)" onkeyup="return limitarelungime(this, 10)" style="width:300px; height:25px"></textarea>
</form>

Email Validation

For this validation we will use two javascript functions: evalid () and everif ().

First check if it's based on something in the email field and somehow was not left empty.

The second function checks if entered text is a typical format for email addresses: if @ contains, if it has at least a point if point is somehow placed immediately before or immediately after it's @ and if perhaps contain more than two characters @.

<script language = "Javascript">
function everif(str) { var at="@"
var punct="."
var lat=str.indexOf(at) var lstr=str.length
var lpunct=str.indexOf(punct)
if (str.indexOf(at)==-1){
alert("Invalid Email. Use a real address !!!")
return false
} if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
alert("Invalid Email. Use a real address !!!")
return false }
if (str.indexOf(punct)==-1 || str.indexOf(punct)==0 || str.indexOf(punct)==lstr){
alert("Invalid Email. Use a real address !!!")
return false
}

if (str.indexOf(at,(lat+1))!=-1){
alert("Invalid Email. Use a real address !!!")
return false
} if (str.substring(lat-1,lat)==punct || str.substring(lat+1,lat+2)==punct){
alert("Invalid Email. Use a real address !!!")
return false
}
if (str.indexOf(punct,(lat+2))==-1){
alert("Invalid Email. Use a real address !!!")
return false
}
if (str.indexOf(" ")!=-1){
alert("Invalid Email. Use a real address !!!")
return false
} return true
} function evalid(){ var emailID=document.eFormular.txtEmail
if ((emailID.value==null)||(emailID.value=="")){
alert("Please enter an email address!")
emailID.focus()
return false
}
if (everif(emailID.value)==false){
emailID.value=""
emailID.focus()
return false
}
return true
} </script>
<form name="eFormular" method="post" action="#" onSubmit="return evalid()">
<p>Enter an Email Address : <input type="text" name="txtEmail"></p>
<p><input type="submit" name="Submit" value="Submit"></p>
</form>

Radio Button and Checkbox Validation

In case there are several variants in response to a question and want to be able to choose only one pass is enough radio buttons the same name that are in question. Vom folosi javascript pentru a ne asigura ca formularul nu va fi trimis fara sa fie bifat un raspuns la fiecare intrebare. We use javascript to ensure that the form will be sent without being checked one answer for each question.

Introduce check_buttons function which will indicate which takes the data to file the form only if you answer every item. Vom verifica asta cu IF, parcurgand inainte fiecare buton ca pe un array cu FOR. We will verify this with RU going through before each button as an array with the FOR.

<script language="Javascript">

 

function check_buttons(){
for(i=0; i<4; i++)
for (j=0; j<4; j++){
if(document.form1.intr1[i].checked==true) {
if(document.form1.intr2[j].checked==true) {
document.form1.action="rezultat.php"; } } } return } </script> <form name="form1" method="post" onSubmit="javascript:check_buttons();" action="">
1. How many programming languages you know?
<p> <input type="radio" name="intr1" value="a">a. None<br>
<input type="radio" name="intr1" value="b">b. 1<br>
<input type="radio" name="intr1" value="c">c. 2<br>
<input type="radio" name="intr1" value="d">d. 3<br> </p>
2. How long are you looking for web design ?
<p>
<input type="radio" name="intr2" value="a">a. Since I was born<br>
<input type="radio" name="intr2" value="b">b. For more than 10 years<br> <input type="radio" name="intr2" value="c">c. Less than 10 years<br>
<input type="radio" name="intr2" value="d">d. Days<br>
</p>
<input type="submit" value="Send form">
</form>

Latest from Valentin


attitude blog

Feedback
My name is

 

Phone

 

Email

 

URL

 

Project Summary (details, timeline, budget, etc.)

 

Attach File (.doc, .docx, .pdf, .txt, .jpg only)