How to validate form input text with javascript - 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;
}
}

Related

How to use onsubmit for form validation, when submit is nested within internal div?

I'm trying to validate a form, by using a validation function, using JS.
When I try to divide the form by using div elements, it doesn't call the validation function anymore.
<form id="myForm" onsubmit="return validateForm();" method="post" action="form-handler.html">
<div>
<label for="firstName">First Name:</label>
<input name="firstName" type="text" placeholder="Jhon">
</div>
<div>
<label for="submit">Submit</label>
<input id="submit" type="Submit" value="send">
</div>
</form>
<script>
function validateForm(form) {
//validation failed if first-name input is empty
if(form.firstName.value == "")
{
alert("Error: Input is empty!");
return false;
}
return true;
}
</script>
Dividing up the form contents with div has no bearing on whether you can invoke a validation function. The problem is that you aren't referring to the element that you want to validate correctly. Your function expects an argument, which you called form, but your code to invoke the function doesn't pass any arguments, so inside your function, form is undefined and therefore you aren't locating the text field you want to validate.
Instead, just reference the element(s) you wish to test:
<form id="myForm" onsubmit="return validateForm();" method="post" action="form-handler.html">
<div>
<label for="firstName">First Name:</label>
<input name="firstName" type="text" placeholder="Jhon">
</div>
<div>
<label for="submit">Submit</label>
<input id="submit" type="Submit" value="send">
</div>
</form>
<script>
function validateForm(evt) {
// Reference the field(s) to validate properly:
if(document.querySelector("[name='firstName']").value == ""){
alert("Error: Input is empty!");
return false;
}
return true;
}
</script>
Now, having said that, don't use inline HTML event attributes, like onsubmit in the first place. That technique is 25+ years old and won't die the death it deserves because of how often people just copy it without understanding why it shouldn't be used. Instead, follow modern standards and separate all your JavaScript from your HTML. Also, your first label is not set up correctly. The for attribute value must match the id of the element that the label is "for".
<form id="myForm" method="post" action="form-handler.html">
<div>
<label for="firstName">First Name:</label>
<input name="firstName" id="firstName" type="text" placeholder="Jhon">
</div>
<div>
<label for="submit">Submit</label>
<input id="submit" type="Submit" value="send">
</div>
</form>
<script>
// Get a reference to the form and set up a submit event handler
document.getElementById("myForm").addEventListener("submit", validate);
// The argument is automatically passed and represents
// the event itself
function validate(evt) {
//validation failed if first-name input is empty
// Properly reference the element(s) you wish to test
if(document.querySelector("[name='firstName']").value == ""){
alert("Error: Input is empty!");
// Tell the event not to proceed.
evt.preventDefault();
}
}
</script>
Option 1:
Change
<form id="myForm" onsubmit="return validateForm();" method="post" action="form-handler.html">
Into
<form id="myForm" onsubmit="return validateForm(this)" method="post" action="form-handler">
To provide the form as an argument to your validateForm function.
Option 2
Change
<label for="firstName">First Name:</label>
<input name="firstName" type="text" placeholder="Jhon">
into
<label for="firstName">First Name:</label>
<input name="firstName" id="firstName" type="text" placeholder="Jhon">
To fix your form and make the input easily selectable in javascript.
Then:
function validateForm(form) {
var firstName = document.getElementById('firstName')
if (firstName.value == "") {
alert("Error: Input is empty!");
return false;
}
return true;
}

Javascript document.forms value does not work for Internet Explorer

I have searched high and low and I cannot figure out why this code works for Chrome/FF but will not work for IE.
function validateForm() {
var x = document.forms["myForm"].elements["fname"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}
<body>
<form name="myForm" action="/action_page_post.php"
onsubmit="return validateForm()" method="post">
<input type="radio" name="fname" id="fname" value="1">1
<input type="radio" name="fname" id="fname" value="2"> 2
<input type="submit" value="Submit">
</form>
</body>
See working demo here: https://www.w3schools.com/code/tryit.asp?filename=FEBA861EAACS
Works on Chrome by not IE
For the first I would suggest to have different IDs for fìdifferent elements
The value attribute is not supported in IE.
elements: The HTMLFormElement.elements property returns an HTMLFormControlsCollection (HTML 4 HTMLCollection) of all the form controls contained in the FORM element, with the exception of input elements which have a type attribute of image.
You can access a particular element by using either an index or the element name or id.
Because you have two radio:
document.forms["myForm"].elements["fname"]
returns a collection (nodelist) not a value. So, you must filter the collection:
function validateForm() {
var x = Array.from(document.forms["myForm"]
.elements["fname"]).filter(function(ele, idx) {
return ele.checked;
});
if (x.length == 0) {
alert("Name must be filled out");
return false;
}
}
A different solution can be based on a different selection strategy:
[document.querySelector('[name="myForm"] [name="fname"]:checked')][2]
The snippet:
function validateForm() {
var x = document.querySelector('[name="myForm"] [name="fname"]:checked');
if (x == null) {
alert("Name must be filled out");
return false;
}
}
<form name="myForm" action="/action_page_post.php"
onsubmit="return validateForm()" method="post">
<input type="radio" name="fname" id="fname1" value="1">1
<input type="radio" name="fname" id="fname2" value="2"> 2
<input type="submit" value="Submit">
</form>

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 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

Checking blank field in text area

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();

Categories

Resources