HTML form validation using JS - javascript

I'm creating form validation, but can't figure out how to use checking preg_match from variable. Checking just for empty fields working fine, but its not enough. Any advice?
var tekst = /([a-zA-Z0-9]|[a-zA-Z0-9])/;
var myForm = document.forms.formaa;
var prek = myForm.elements['preke'];
var kaina = myForm.elements['kaina'];
var k = myForm.elements['kiekis'];
var uzsak = myForm.elements['uzsakymas'];
if (uzsak.value == ''){
alert("neuzpildyta");
return false;
}
for (var i = 0; i < prek.length; i++) {
var preke = prek[i];
var kai = kaina[i];
var kie = k[i];
if (preke.value == '' || (preke.value).test(tekst) == false){
alert("neuzpildyta");
return false;
}
if (kai.value == ''){
alert("neuzpildyta");
return false;
}
if (kie.value == ''){
alert("neuzpildyta");
return false;
}
}

You can also use like this,
if (x==null || x=="") {
document.getElementById('name').innerHTML="Name must be filled out";
return false; }
For More This one help's you JavaScript Validation.

Rather than rolling your own validation, have you considered using something like jQuery validation?

Related

How should I improve my javascript form validation?

I grabbed the form from some random site because I'm only interested writing the javascript at the moment.
I am trying to check that a user has selected or entered text for all fields. I've made it a long if if-else but that can't be the best/most elegant/easiest solution.
Leaving aside the radio button validation for now, what's the better way to check that the text fields, drop down, and checkboxes all have a value/input?
I'm teaching myself javascript so I'm open to being told the proper way and I'll research it and do it on my own, or updating my fiddle would be fine too. (Be gentle with me. I'm sure this code is janky.)
Any thoughts on this would be appreciated.
Fiddle: https://jsfiddle.net/kiddigit/g0rur21a/
document.getElementById("newForm").addEventListener("submit", enterForm);
function enterForm(event) {
event.preventDefault();
var dropdown = document.getElementById('dropDown');
if (document.getElementById('fname').value === ''){
document.getElementById('fname').focus();
alert('Enter text.');
} else if (document.getElementById('eMail').value === ''){
document.getElementById('eMail').focus();
alert('Enter text.');
} else if (document.getElementById('textArea').value === '') {
document.getElementById('textArea').focus();
alert('Enter text.');
} else if (!dropDown.value) {
document.getElementById('dropDown').focus();
alert('Choose an option.');
} else if ( ( newForm.checkbox[0].checked == false ) && ( newForm.checkbox[1].checked == false ) )
{ alert ( "Please choose a checkbox" );
return false;
}
var radios = document.getElementsByName("radio");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Please check a radio button.");
return formValid;
return false;
};
If you use HTML5, and assuming you're NOT using jQuery for anything (just native JavaScript), a good convention would be to assign a class to all input elements in the form that you want to validate (or if they all need to be validated, you can get all child elements of the form), and use getElementsByClassName(). With HTML5 data-* attributes, you can assign something like data-invalid-error-message to set the error message for the element itself.
http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
From there, you can perform a loop across all elements, check if they're empty, and then grab the data-invalid-error-message attribute and display it to the user without doing nested if statements.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
document.getElementById("newForm").addEventListener("submit", function (event) {
event.preventDefault();
if (!document.getElementById('fname').value) {
return alert('Enter text.');
}
if (document.getElementById('eMail').value === '') {
document.getElementById('eMail').focus();
return alert('Enter text.');
}
if (document.getElementById('textArea').value === '') {
document.getElementById('textArea').focus();
return alert('Enter text.');
}
var dropdown = document.getElementById('dropDown');
if (!dropdown || !dropDown.value) {
document.getElementById('dropDown').focus();
return alert('Choose an option.');
}
if (( newForm.checkbox[0].checked == false ) && ( newForm.checkbox[1].checked == false )) {
return alert("Please choose a checkbox");
}
var radios = document.getElementsByName("radio");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) {
formValid = true;
}
i++;
}
if (!formValid) {
return alert("Please check a radio button.");
}
// Form is valid here
});
Here is some improvements. Updated Fiddle
I would like to validate form with required property, but it does not support validation of group of options and radio groups
If you're OK not supporting IE8, you can use querySelectorAll to dynamically get all the nodes of different types within your form and validate them accordingly. This will work for a form with any number of inputs:
function validateForm(formNode) {
var formValid = true;
var textFlds = formNode.querySelectorAll('input[type="text"],input[type="email"],input[type="password"],textarea');
var dropdowns = formNode.querySelectorAll('select');
var checks = formNode.querySelectorAll('input[type="checkbox"]');
var anyChecked = false;
var radios = formNode.querySelectorAll('input[type="radio"]');
var anyRadios = false;
for (var i = 0, l = textFlds.length; i < l; i++) {
if (!textFlds[i].value) {
textFlds[i].focus();
alert('Please enter text into the ' + textFlds[i].name + ' field.');
formValid = false
break;
}
};
for (var i = 0, l = dropdowns.length; i < l; i++) {
if (formValid && !dropdowns[i].value) {
dropdowns[i].focus();
alert('Please choose an option from the ' + dropdowns[i].name + ' selector.');
formValid = false
break;
}
};
for (var i = 0, l = checks.length; i < l; i++) {
if (checks[i].checked) {
anyChecked = true;
break;
}
};
if (formValid && !anyChecked) {
alert('Please choose at least one of the checkboxes.');
formValid = false;
}
for (var i = 0, l = radios.length; i < l; i++) {
if (radios[i].checked) {
anyRadios = true;
break;
}
};
if (formValid && !anyRadios) {
alert('Please check a radio button.');
formValid = false;
}
return formValid;
}
document.getElementById('newForm').addEventListener('submit', function (evt) {
evt.preventDefault();
validateForm(this);
});
This could be prettied up a bit, but you get the idea. (fiddle here)

How to validate an input as an number in JavaScript

I'm new with JavaScript programming and have been trying to validate a number that is inputted from a user on a php page. Here is the javascript that is included.
var validate_and_create = function(){
var i_number = $("input_number").value;
var isValid = true;
if (i_number === ""){
$("create_n_error").firstChild.nodeValue = "Number text field cannot be blank.";
isValid = false;
} else {
if (typeof i_number === 'number') {
$("create_n_error").firstChild.nodeValue = "This is a number!";
isValid = true;
} else {
$("create_n_error").firstChild.nodeValue = "This is not a number!";
isValid = false;
}
}
It always prints that the input is not a number even when integer values are inserted in the textbox. So I'm sure its taking the input as a string input. So do I have to convert it to integer so I can validate? or am I doing something wrong?
You can use parseInt to convert the value to integer, like parseInt("55", 10) will return 55.
And something like parseInt("xx",10) returns NaN.
Thanks adeneo, isNaN works for validation.
Code below:
var validate_and_create = function(){
var i_number = $("input_number").value;
var isValid = true;
if (i_number === ""){
$("create_n_error").firstChild.nodeValue = "Number text field cannot be blank.";
isValid = false;
} else {
if (isNaN(i_number)) {
$("create_n_error").firstChild.nodeValue = "This is not a number!";
isValid = false;
} else {
$("create_n_error").firstChild.nodeValue = "This is a number!";
isValid = true;
}
}

Validating using JavaScript - how to show to all validation error message's

I have function that checks if fields are blank but if all fields are blank it only shows one of the validation message's, I think this is because I have used an if statement:
function validateForm()
{
var sName=document.forms["myForm"]["surname_5"].value;
if (sName==null || sName=="")
{
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
return false;
}
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("fNameMessage").innerHTML = "*First name is required";
return false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("titleMessage").innerHTML = "You need to select a title";
return false;
}
}
How do I get it so all validation messages show if the user has left all fields blank?
Don't return false immediately. Set a variable to false (after defining it as true at the very start of the function) and return that variable at the end.
Try something like this (or add all your code if you need more details)
JavaScript:
function validateForm() {
var sName = document.forms["myForm"]["surname_5"].value;
var ret = true;
if (sName == null || sName == "") {
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
ret = false;
}
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "*First name is required";
ret = false;
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
ret = false;
}
return ret;
}

If conditions is not working in javascript injection

I am working on a project where i want to change the value of the desired text boxes in the web page.
I am using javascript injection to the web browser to paste the values of the text fields.
In the code below, I have taken a activeElement in the document and compare it with other element in the element List. and want to paste another string in the next text field. But in the below code the if----elseif--- condition is not working as desired.
var editcount = document.getElementsByTagName('input');
var fcElement = document.activeElement;
var cpt = 0;
var bFlag = false;
for (cpt = 0; cpt < editcount.length; cpt++) {
if (editcount[cpt].id == fcElement.id && !bFlag) {
fcElement.value = "Username";
bFlag = true;
}
else if((editcount[cpt].type == "password"||editcount[cpt].type == "text" || editcount[cpt].type == "email") && bFlag === true) {
editcount[cpt].value = "Password";
break;
}
}
Here, the password is also copied on the same text field.
can anyone tell me whats wrong with the script ?
Thank you for your help.
I was having problem with my code.
I was comparing the ids of the two elements.
if (editcount[cpt].id == fcElement.id && !bFlag)
and this was not working for some web pages but now I got the solution for it.
I have changed the condition of comparision of elements as below.
if (editcount[cpt].name == fcElement.name && !bFlag)
and My problem has solved.
I am posting my working code here...
`
var editcount = document.getElementsByTagName('input');
var fcElement = document.activeElement;
var cpt = 0;
var bFlag = false;
console.log(fcElement);
for (cpt = 0; cpt < editcount.length; cpt++) {
console.log(editcount[cpt]);
if (editcount[cpt].name == fcElement.name) {
fcElement.value = "Username";
bFlag = true;
} else if ((editcount[cpt].type == "password" || editcount[cpt].type == "text" || editcount[cpt].type == "email") && bFlag === true) {
editcount[cpt].value = "Password";
break;
}
}`
Thank you for your cooperation.
Merry Christmas.

Disable submit until form is filled javascript

I need to disable the submit button until all fields are filled with the rules any tips?
window.onload = $("input[type=submit]").attr("disabled", "disabled");
$(function(){
$("input[type=submit]").attr("disabled", "disabled");
var total = document.getElementById('valor_total'),
descontado = document.getElementById('valor_descontado'),
valor_final = document.getElementById('valor_final'),
vendedor = document.getElementById('vendedor'),
cliente = document.getElementById('cliente'),
no_contrato = document.getElementById('contrato'),
validation;
var f_total = total.value;
var f_descontado = descontado.value;
var f_final = valor_final.value;
var f_vendedor = vendedor.value;
var f_cliente = cliente.value;
var f_no_contrato = no_contrato.value;
$("#numero_contrato").blur(function() {
if ( f_vendedor == "0" || f_cliente == "0" || f_no_contrato == "" || f_total == "0,00" || f_final == "0,00") {
validation = false;
} else {
validation = true;
}
if (validation = true) {
$("input[type=submit]").removeAttr("disabled");
} else {
$("input[type=submit]").attr("disabled", "disabled");
}
});
});
what i'm doin wrong?
I want that user type in the field with id numero_contrato the function runs and enable or not the submit
For starters, try fixing this conditional:
if (validation === true) {
$('input[type=submit]').removeAttr('disabled');
} else {
$('input[type=submit]').attr('disabled', 'disabled');
}
You had a single equals which is used for assignment. You want double or preferably, triple equals. But you can drop those entirely since you're using a boolean: if (validation) { ... }

Categories

Resources