Unable to validate form elements - javascript

I am trynig to learn how to validate form elements using their IDs. I also made a fiddle to check and try manipulating the code but the fiddle is showing error. Here is the fiddle https://jsfiddle.net/obz3jc30/ There is definitely something wrong in the code because of which I am unable to validate. Need help in identifying the issue
HTML
<form name="Form1">
Age :
<input value="" name="Fromage" type="text" id="Fromage">
to
<input value="" name="Toage" type="text" id="Toage">
<button class="check" onclick="function()">Validate</button>
</form>
Script
$('.check').click(function() {
var af=Form1.Fromage.value;
if (af.length == 0 )
{
alert( "Please Enter Age From." );
Form1.Fromage.focus( );
return false;
}
if(h.length>0)
{
if((af.length<2)||(af.length>2))
{
alert( "Age should be 2 digits");
Form1.Fromage.focus( );
return false;
}
else
{
var af3=/[^1-9]/;
if(af.match(af3)!=null)
{
alert( "Please Enter Valid Age");
Form1.Fromage.focus( );
return false;
}
}
}
return true;
}

Related

Trying to convert this big if else statement into a loop

Hi I'm trying to make this code more clean. I struggle with arrays and loops and have no idea how to convert this into into a loop. This is javascript for a form on an html page and if they leave a field blank, when they hit submit it should return an alert box and if everything is submitted properly it should confirm with them. There's also a reg exp for an acceptable postal code entry.
function validate()
{
var register = document.forms[0];
if (register.fname.value === "")
{
alert("Please fill out your first name.");
return false;
}
else if(register.lname.value === "")
{
alert("Please fill out your last name.");
return false;
}
else if(register.address.value === "")
{
alert("Please fill out your address.");
return false;
}
else if(register.postal.value ==="")
{
alert("Please enter a valid postal code.");
return false;
}
else if(!checkPostal(register.postal.value))
{
alert("Please enter a valid postal code.");
return false;
}
else if(register.eAddress.value === "")
{
alert("Please fill out your email address.");
return false;
}
return confirm("Is the information correct?");
}
//postal code regExp
function checkPostal()
{
var myReg = /^[A-Z]\d[A-Z] ?\d[A-Z]\d$/ig;
return myReg.test(document.getElementById("postal").value);
}
You can make this a pure HTML solution if you want to reduce javascript:
inputs have a required attr ref
additionally, inputs have a pattern attr ref that supports regex.
This kind of solution lets the browser handle feedback
<form>
<label>first name:
<input type="text" name="fname" required
minlength="1">
</label><br/>
<label>last name:
<input type="text" name="lname" required
minlength="1">
</label><br/>
<label>postal code:
<input type="text" name="zip" required pattern="^[A-Z]\d[A-Z] ?\d[A-Z]\d$"
minlength="1">
</label><br/>
<input type="submit" />
</form>
$.each( $( "#input input" ), function( key, element ) {
if( !$(element).val() ) {
$( "#error" + key ).text( "Input " + $( element ).attr( "name" ) + " is required");
return false;
}
});
Set your message as attribute on each element of the form like this:
<form method="POST" action="submit.php">
<input id="item1" type="text" value="" data-message="My error message" data-must="true">
...//do the same for other elements...
</form>
Now loop like below
var elements = document.forms[0].elements;
for (var i = 0, element; element = elements[i++];) {
if (element.getAttribute("must") && element.value === ""){
alert(element.getAttribute("message"));
return false;
}
}
return confirm("Is the information correct?");

JavaScript Email address validation

I am making an HTML form with fields validation using JavaScript. I am stuck on email validation. I searched internet and found something like this-
JS Code
function validateemail() {
var x=document.myform.email.value;
var atposition=x.indexOf("#");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length) {
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
HTML Code
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
Please explain me this?
Check this i am using something like this i minified some of them
You must Enter Valid Email address something like this Example#example.com
$(document).ready(function() {
$('.insidedivinput').focusout(function() {
$('.insidedivinput').filter(function() {
var emil = $('.insidedivinput').val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (emil.length == 0) {
$('.fa-check').css('display', 'none');
$('.fa-close').css('display', 'inline');
$('.sendmailbuttontrigger').attr('disabled', 'disabled');
$('.SendEmail').attr('disabled', 'disabled');
} else if (!emailReg.test(emil)) {
$('.SendEmail').attr('disabled', 'disabled');
$('.sendmailbuttontrigger').attr('disabled', 'disabled');
$('.fa-check').css('display', 'none');
$('.fa-close').css('display', 'inline');
} else {
// alert('Thank you for your valid email');
$('.fa-close').css('display', 'none');
$('.sendmailbuttontrigger').removeAttr('disabled');
$('.fa-check').css('display', 'inline');
}
})
});
});
.fa-check{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='email' class='insidedivinput'><i class='fa-check'>Validated</i><i class="fa-close">UnValidated</i>
<button class="sendmailbuttontrigger" disabled>
Send
</button>
If you just want to validate an email address, you can use the validation that's built into HTML:
<form onsubmit="return false;">
<input type="email" required="1">
<input type="submit">
</form>
(Leave out the onsubmit for your own form, of course. It's only in my example to keep you from leaving the page with the form.)
I also searched on the Internet and use this one and it's working.
// email validation
checkEmail = (inputvalue) => {
const pattern = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
if (pattern.test(inputvalue)) return true;
return false;
}

Validation with JavaScript

There are similar questions, but I can't find the way I want to check the form submit data.
I like to check the form submit data for phone number and email. I check as follows, but it doesn't work.
How can I make it correct?
<script>
function validateForm() {
var x = document.forms["registerForm"]["Email"].value;
if (x == null || x == "") {
alert("Email number must be filled out.");
return false;
}
else if(!/#./.test(x)) {
alert("Email number must be in correct format.");
return false;
}
x = document.forms["registerForm"]["Phone"].value;
if (x == null || x == "" ) {
alert("Phone number must be filled out.");
return false;
}
else if(!/[0-9]+()-/.test(x)) {
alert("Phone number must be in correct format.");
return false;
}
}
</script>
For email I'd like to check only "#" and "." are included in the email address.
For phone number, I'd like to check ()-+[0-9] and one space are only accepted for phone number, for example +95 9023222, +95-1-09098098, (95) 902321. How can I check it?
There will be another check at the server, so there isn't any need to check in detail at form submit.
Email validation
From http://www.w3resource.com/javascript/form/email-validation.php
function ValidateEmail(mail)
{
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
Phone number validation
From http://www.w3resource.com/javascript/form/phone-no-validation.php.
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if ((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
You can do something like this:
HTML part
<div class="form_box">
<div class="input_box">
<input maxlength="64" type="text" placeholder="Email*" name="email" id="email" />
<div id="email-error" class="error-box"></div>
</div>
<div class="clear"></div>
</div>
<div class="form_box">
<div class="input_box ">
<input maxlength="10" type="text" placeholder="Phone*" name="phone" id="phone" />
<div id="phone-error" class="error-box"></div>
</div>
<div class="clear"></div>
</div>
Your script
var email = $('#email').val();
var phone = $('#phone').val();
var email_re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,3}))$/;
var mobile_re = /^[0-9]{10}$/g;
if ($.trim(email) == '') {
$('#email').val('');
$('#email-error').css('display', 'block');
$('#email-error').html('Please enter your Email');
} else if (!email.match(email_re)) {
$('#email-error').css('display', 'block');
$('#email-error').html('Please enter valid Email');
}
if ($.trim(phone) == '') {
$('#phone').val('');
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please enter your Phone Number');
} else if (!phone.match(mobile_re)) {
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please enter valid Phone Number');
} else {
$('#phone-error').css('display', 'none');
$('#phone-error').html('');
}
You could of course write the validation part yourself, but you could also use one of the many validation libraries.
One widely used one is Parsley. It's very easy to use. Just include the .js and .css and add some information to the form and its elements like this (fiddle):
<script src="jquery.js"></script>
<script src="parsley.min.js"></script>
<form data-parsley-validate>
<input data-parsley-type="email" name="email"/>
</form>
HTML5 has an email validation facility. You can check if you are using HTML5:
<form>
<input type="email" placeholder="me#example.com">
<input type="submit">
</form>
Also, for another option, you can check this example.

First time running but not working from 2nd time

I am working with a javascript function which works first time but not from the 2nd time.The console shows: Uncaught TypeError: pizza_name is not a function
My html is :
<div class="pizza_name_div">
<input type="text" name="pizza_name" id="pizza_name" placeholder="Enter your pizza name as u like. i.e : my-pizza" value="">
<input type="submit" value="Go" id="pizza_name_submit" onclick="pizza_name()">
</div>
And My js
function pizza_name() {
if( pizza_name != "" ) {
.........
}else{
alert( "please enter a name" );
}
}
It shows alert properly for 1st time.But not form 2nd
Link
js code:
function pizza_name() {
var pizzaName=document.getElementById("pizza_name").value;
if(!pizzaName ) {
alert("no value");
}else{
alert( "please enter a name" );
}
}
Change your code with:
function pizza_name() {
var pizzaName = document.getElementById('pizza_name').value;
if(pizzaName != "") {
//.........
} else {
alert( "please enter a name" );
}
}
It's very important to not assign any value to a possible pizza_name variable inside the function.
You can use jquery for this too
HTML
<div class="pizza_name_div">
<input type="text" name="pizza_name" id="pizza_name" placeholder="Enter your pizza name as u like. i.e : my-pizza" value="">
<input type="submit" value="Go" id="pizza_name_submit" >
</div>
JQUERY
$(document).ready(function(){
$("#pizza_name_submit").on("click", function(){
if( $("#pizza_name").val()) {
alert( $("#pizza_name").val());
}else{
alert("enter value");
}
});
});
demo
Don't re-use names, you're probably overwriting your function to be a string instead.
(that's what I'm assuming happens in the code you didn't show since you're trying to test pizza_name as a string)
function pizza_name() {
if( pizza_name != "" )
You'd be better off naming the function something like getPizzaName. Name the function for what it does, not what it returns.

validation in javascript - remove the error msg on focus

i'm not very well-versed with javascript, so please bear with me.
i've a form in which i validate the controls with javascript. the error is displayed when the fields are empty via a div, but when i focus and type something in the textbox, the div should go away. but the error div doesn't and even if i type something valid, it still displays the div.
i'd like to know where am i going wrong with this script:
<script type="text/javascript">
var err = document.getElementById("errmsg");
function checkInput(inPut) {
if (inPut.getValue() == "") {
err.setStyle('display', 'block');
err.setTextValue("Field cannot be empty!");
inPut.focus();
return false;
}
else {
return true;
}
}
function checkTextBox(textBox)
{
if (textBox.getValue() == "") {
err.setStyle('display', 'block');
err.setTextValue("Field cannot be empty!");
textBox.focus();
return false;
}
else if (!checkValidity(textBox.getValue())) {
err.setStyle('display', 'block');
err.setTextValue("Please enter a valid email address!");
textBox.focus();
return false;
}
else {
return true;
}
}
. . .
<div id="errmsg" class="invalid" style="display:none;"></div> <br />
. . .
<input type="text" tabindex="1" name="name" id="name" class="input_contact" onblur="checkInput(this);"/> <br />
. . .
<input type="text" tabindex="2" name="email" id="email" class="input_contact" onblur="checkTextBox(this);"/> <br />
it's a form in facebook app but while the fbjs works, i assume there's a problem with my basic javascript.
try this
var err = document.getElementById("errmsg");
function checkInput(inPut) {
if (inPut.getValue() == "") {
err.setStyle('display', 'block');
err.setTextValue("Field cannot be empty!");
inPut.focus();
return false;
}
else {
err.setStyle('display', 'none');
err.setTextValue("");
return true;
}
}
function checkTextBox(textBox)
{
if (textBox.getValue() == "") {
err.setStyle('display', 'block');
err.setTextValue("Field cannot be empty!");
textBox.focus();
return false;
}
else if (!checkValidity(textBox.getValue())) {
err.setStyle('display', 'block');
err.setTextValue("Please enter a valid email address!");
textBox.focus();
return false;
}
else {
err.setStyle('display', 'none');
err.setTextValue("");
return true;
}
}
To get the div to disappear when you first type something, instead of when the field is checked, you'll also need onchange and/or onfocus event handlers for the fields:
<input type="text" tabindex="1" name="name" id="name" class="input_contact"
onblur="checkInput(this);"
onfocus="err.setStyle('display', 'none');"
onchange="err.setStyle('display', 'none');"
/>
They could also be set inside checkInput(), if you so desire.

Categories