I'm trying to create a simple validation script which checks if text was entered or not in a textbox. I wrote the following code, which unfortunately does not print the alert.
<html>
<head>
<title> Js Page </title>
<script>
function validateName()
{
var FirstName=document.forms["myForm"]["firstname"].value;
if(FirstName==null || FirstName=="" )
{
alert("Please insert the corect First/Lastname");
return false;
}
}
</script>
</head>
<body>
<form name = "myForm" onsubmit = "return validateName()" method="post">
First name: <input type="text" name="firstname"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
It is better to use id
<input type="text" name="firstname" id="firstnameId">
function validateName()
{
if(document.getElementById("firstnameId").value == ""){
alert("Please insert the corect First/Lastname");
return false;
} else
return true;
}
From firefox error console:
Timestamp: 6/29/2013 5:37:41 PM Error: SyntaxError: missing } after
function body Source File:
file:///C:/Users/developer/Desktop/adad.html Line: 13
You're missing } in function body.
function validateName()
{
var FirstName=document.forms["myForm"]["firstname"].value;
if(FirstName==null || FirstName=="" )
{
alert("Please insert the corect First/Lastname");
return false;
}
}
you are miising "}" at the in your jaavascript function
try to add developer tools of your browser it is advisable to use.
Maybe it would ignore the emptiness because of the space characters. You should use trim().
var FirstName = document.forms["myForm"]["firstname"].value.trim();
if(FirstName == ""){
}
is good for checking emptiness.
you can also use jQuery:
(give id="firstname" in your textox)
$(document).ready(function() {
$('#login').click(function() {
var username = $('#firstname').val();
if ($.trim(username).length == 0) {
alert('Please enter User name.');
return false;
e.preventDefault();
}
});
});
this is the complete validation for email
<script>
function validateForm()
{
var x=document.forms["register"]["email"].value;
var atpos=x.indexOf("#");
var space=x.indexOf(" ");
var dollar=x.indexOf("$");
var hash=x.indexOf("#");
var per=x.indexOf("%");
var or=x.indexOf("^");
var amber=x.indexOf("&");
var star=x.indexOf("*");
var plus=x.indexOf("+");
var minus=x.indexOf("-");
var coma=x.indexOf(",");
var dotpos=x.lastIndexOf(".");
var neg=x.indexOf("~");
var neq=x.indexOf("!");
var b1=x.indexOf(")");
var b2=x.indexOf("(");
var b3=x.indexOf(":");
var b5=x.indexOf("?");
var b6=x.indexOf(">");
var b7=x.indexOf("<");
var b8=x.indexOf("}");
var b9=x.indexOf("{");
var b10=x.indexOf("|");
if (x==null || x=="")
{
alert("Email is mandatory");
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length || space>0 || dollar>0 || hash>0 || per>0 || or>0 || amber>0 || star>0 || plus>0 || minus>0 || coma>0 || neg>0 || neq>0 || b1>0 || b2>0 || b3>0 || b5>0 || b6>0 || b7>0 || b8>0 || b9>0 || b10>0)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
<form name="register" onsubmit="return validateForm()" action='http:\\www.google.com' method='get'>
<font face="Times New Roaman">Email Address*</font></td><td><input type='text' name='email' value='example#domain.com' onblur="if (this.value == '') {this.value = 'example#domain.com';}"
onfocus="if (this.value == 'example#domain.com') {this.value = '';}">
<input type='submit' value='submit'>
</form>
Related
I'm trying to validate a form using JavaScript, but the code doesn't seem to execute. The Form is being processed using php which is working just fine. But, the validation is not working. Can someone please help me with this.
<script>
function validateForm(){
var x = document.getElementById('name');
var email = document.getElementById('email');
var num = document.getElementById('number');
var size = document.getElementById('size');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var atpos=email.value.indexOf("#");
var dotpos=email.value.lastIndexOf(".");
if (x.value == null || x.value == "") {
alert("Please Enter your name");
x.foucs;
x.style.background = 'Yellow';
return false;
}
if(!filter.test(email.value){
alert('Please provide a valid email address');
email.focus;
email.value="";
return false;
}
if(num.value == null && num.value == ""){
alert('Please enter your mobile number');
num.focus();
}
if(!isNan(num.value){
alert('Please enter a valid number');
num.focus();
num.style.background();
return false;
}
return false;
}
</script>
And here is my html code.
<form method="post" name="myForm " onsubmit="return validateForm()" action="myprocessingscript.php" >
<input type="text" name="name" placeholder="Name" class="text" id="name" />
<input name="email" placeholder="Email" type="text" class="text" id="email"/>
<input name="number" placeholder="Mobile Number" type="text" class="text" id="number"/>
<input name="size" placeholder="Size" type="text" class="text" id="size" />
<input type="Submit" value="Submit" class="button">
Working fiddle
Correct the spelling of foucs and ensure all references have parenthesis such as:
email.focus();
Without parenthesis, the function is not called. It's valid Javascript but it won't do anything.
You also missed a closing ) here:
if(!filter.test(email.value){
// ^ add another )
and here:
if(!isNan(num.value){
// ^ add another )
!isNan(....) should be isNaN(....). Javascript is case sensitive and you shouldn't be "notting" it here. isNaN is saying "is not a number" so it's already "notted".
On the line below, style has no background function. Looks like you want to assign a value here not call a function:
num.style.background(); // change to assign value.
On this line, change && to ||:
if(num.value == null && num.value == ""){
// ^ should be ||
Finally, remove the return false at the end.
Try using x.focus();
x.foucs; is not a valid statement, and neither is email.focus;.
These aren't right I don't think:
email.focus;
// Try email.focus();
and
x.foucs;
// Try x.focus();
Also looking at your code I don't see a </form>
Try this:
function validateForm(){
var x = document.getElementById('name');
var email = document.getElementById('email');
var num = document.getElementById('number');
var size = document.getElementById('size');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (x.value == null || x.value == "") {
alert("Please Enter your name");
x.focus();
x.style.background = 'Yellow';
return false;
}
if(!filter.test(email.value){
alert('Please provide a valid email address');
email.focus();
email.value="";
return false;
}
if(num.value == null || num.value == ""){
alert('Please enter your mobile number');
num.focus();
return false;
}
if(!isNaN(num.value)){
alert('Please enter a valid number');
num.focus();
num.style.background = "Yellow";
return false;
}
return true;
}
I can't figure out why this is not working as i did everything correct.
This is a simple create a account form. I put validation code for some of the field like name, email and password. There are many other fields. but first i m trying this.
The like is here:
jsfiddle
and the code of HTML:
First Name
<input type="text" name="fname" id="fname"/>
<input type="text" name="lname" id="lname />
<input type="text" name="remail" id="remail" />
New Pasword
<input type="password" name="rpass" id="rpass" />
<input name="regis" type="submit" class="color2" id="id" value="Submit" />
The javascript code here:
function validateRegis() {
//regex for fname and lname
var fname = $("#fname").val();
var lname = $("#lname").val();
var patt_n = /[a-z]{2,20}/i;
//checking fname and lname for regex matching
var ftest = patt_n.test(fname);
var ltest = patt_n.test(lname);
var remail = $("#remail").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9\_\.\-]+[a-zA-Z0-9\_\-]+#[a-zA-Z0-9]+[a-zA-Z0-9\.\-]+[a-zA-Z0-9]+\.[a-z]{2,4}$/;
var test = filter.test(remail);
var rpass = $("#rpass").val();
var patt = /[a-z0-9~!##$%^&*()_\ ]/i;
var test2 = patt.test(rpass);
if (fname === "" || ftest === false) {
alert("Please provide first name!");
$("#fname").focus();
return false;
} else if (lname === "" || ltest === false) {
alert("Please provide Last name!");
$("#lname").focus();
return false;
} else if (remail === "" || test === false) {
//
alert("Please provide email in correct format!");
$("#remail").focus();
return false;
} else if (rpass === "" || rpass.length < 8 || test2 === false) {
alert("Please provide password!");
$("#rpass").focus();
return false;
} else if ((fname !== "") & (lname !== "") & (remail !== "") & (test === true) & (rpass >= 8) & test2 === true) {
return true;
}
}
It needs jquery to run the code.
The problem is the validateRegis function is not available in the global scope.
In the fiddle UI left side panel, 2nd select box select No Wrap in body, it works fine.
Demo: Fiddle
When you select onLoad there, all the scripts under the script frame is wrapped under a anonymous function, so your validateRegis method becomes a local member of that anonymous function. Thus that function will not be available when the function submit is called causing an Uncaught ReferenceError: validateRegis is not defined error being thrown.
<script type='text/javascript'>
function required()
{
var empt = document.forms["form1"]["Name"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
}
</script>
<form name="form1" method="" action="">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="address line1" value="Address Line 1"/><br />
I have more than one input text field, each having their default value. Before I submit the form I have to verify whether all fields are filled. So far i got the javascript to check for null since different text boxes have different default value. How can I write a javascript to verify that user has entered data? I mean, the script must identify that input data is other than default and null.
If you are not using jQuery then I would simply write a validation method that you can be fired when the form is submitted. The method can validate the text fields to make sure that they are not empty or the default value. The method will return a bool value and if it is false you can fire off your alert and assign classes to highlight the fields that did not pass validation.
HTML:
<form name="form1" method="" action="" onsubmit="return validateForm(this)">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="addressLine01" value="Address Line 1"/><br />
<input type="submit"/>
</form>
JavaScript:
function validateForm(form) {
var nameField = form.name;
var addressLine01 = form.addressLine01;
if (isNotEmpty(nameField)) {
if(isNotEmpty(addressLine01)) {
return true;
{
{
return false;
}
function isNotEmpty(field) {
var fieldData = field.value;
if (fieldData.length == 0 || fieldData == "" || fieldData == fieldData) {
field.className = "FieldError"; //Classs to highlight error
alert("Please correct the errors in order to continue.");
return false;
} else {
field.className = "FieldOk"; //Resets field back to default
return true; //Submits form
}
}
The validateForm method assigns the elements you want to validate and then in this case calls the isNotEmpty method to validate if the field is empty or has not been changed from the default value. it continuously calls the inNotEmpty method until it returns a value of true or if the conditional fails for that field it will return false.
Give this a shot and let me know if it helps or if you have any questions. of course you can write additional custom methods to validate numbers only, email address, valid URL, etc.
If you use jQuery at all I would look into trying out the jQuery Validation plug-in. I have been using it for my last few projects and it is pretty nice. Check it out if you get a chance. http://docs.jquery.com/Plugins/Validation
<form name="myForm" id="myForm" method="post" onsubmit="return validateForm();">
First Name: <input type="text" id="name" /> <br />
<span id="nameErrMsg" class="error"></span> <br />
<!-- ... all your other stuff ... -->
</form>
<p>
1.word should be atleast 5 letter<br>
2.No space should be encountered<br>
3.No numbers and special characters allowed<br>
4.letters can be repeated upto 3(eg: aa is allowed aaa is not allowed)
</p>
<button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>
validateForm = function () {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
var errMsgHolder = document.getElementById('nameErrMsg');
if (input.length < 5) {
errMsgHolder.innerHTML =
'Please enter a name with at least 5 letters';
return false;
} else if (!(/^\S{3,}$/.test(input))) {
errMsgHolder.innerHTML =
'Name cannot contain whitespace';
return false;
}else if(!(/^[a-zA-Z]+$/.test(input)))
{
errMsgHolder.innerHTML=
'Only alphabets allowed'
}
else if(!(/^(?:(\w)(?!\1\1))+$/.test(input)))
{
errMsgHolder.innerHTML=
'per 3 alphabets allowed'
}
else {
errMsgHolder.innerHTML = '';
return undefined;
}
}
.error {
color: #E00000;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Validation</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var tags = document.getElementsByTagName("input");
var radiotags = document.getElementsByName("gender");
var compareValidator = ['compare'];
var formtag = document.getElementsByTagName("form");
function validation(){
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
//Validation for Textbox Start
if(tags[i].type == "text"){
if(tagval == "" || tagval == null){
var lbl = $(tags[i]).prev().text();
lbl = lbl.replace(/ : /g,'')
//alert("Please Enter "+lbl);
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Please Enter "+lbl+"</span>");
$("#"+tagid).focus();
//return false;
}
else if(tagval != "" || tagval != null){
$(".span"+tagid).remove();
}
//Validation for compare text in two text boxes Start
//put two tags with same class name and put class name in compareValidator.
for(var j=0;j<compareValidator.length;j++){
if((tagval != "") && (tagclass.indexOf(compareValidator[j]) != -1)){
if(($('.'+compareValidator[j]).first().val()) != ($('.'+compareValidator[j]).last().val())){
$("."+compareValidator[j]+":last").after("<span style='color:red;' class='span"+tagid+"'>Invalid Text</span>");
$("span").prev("span").remove();
$("."+compareValidator[j]+":last").focus();
//return false;
}
}
}
//Validation for compare text in two text boxes End
//Validation for Email Start
if((tagval != "") && (tagclass.indexOf('email') != -1)){
//enter class = email where you want to use email validator
var reg = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(tagval)){
$(".span"+tagid).remove();
return true;
}
else{
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Email is Invalid</span>");
$("#"+tagid).focus();
return false;
}
}
//Validation for Email End
}
//Validation for Textbox End
//Validation for Radio Start
else if(tags[i].type == "radio"){
//enter class = gender where you want to use gender validator
if((radiotags[0].checked == false) && (radiotags[1].checked == false)){
$(".span"+tagid).remove();
//$("#"+tagid").after("<span style='color:red;' class='span"+tagid+"'>Please Select Your Gender </span>");
$(".gender:last").next().after("<span style='color:red;' class='span"+tagid+"'> Please Select Your Gender</span>");
$("#"+tagid).focus();
i += 1;
}
else{
$(".span"+tagid).remove();
}
}
//Validation for Radio End
else{
}
}
//return false;
}
function Validate(){
if(!validation()){
return false;
}
return true;
}
function onloadevents(){
tags[tags.length -1].onclick = function(){
//return Validate();
}
for(var j=0;j<formtag.length;j++){
formtag[j].onsubmit = function(){
return Validate();
}
}
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
if((tags[i].type == "text") && (tagclass.indexOf('numeric') != -1)){
//enter class = numeric where you want to use numeric validator
document.getElementById(tagid).onkeypress = function(){
numeric(event);
}
}
}
}
function numeric(event){
var KeyBoardCode = (event.which) ? event.which : event.keyCode;
if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57)){
event.preventDefault();
$(".spannum").remove();
//$(".numeric").after("<span class='spannum'>Numeric Keys Please</span>");
//$(".numeric").focus();
return false;
}
$(".spannum").remove();
return true;
}
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", onloadevents, false);
}
//window.onload = onloadevents;
</script>
</head>
<body>
<form method="post">
<label for="fname">Test 1 : </label><input type="text" title="Test 1" id="fname" class="form1"><br>
<label for="fname1">Test 2 : </label><input type="text" title="Test 2" id="fname1" class="form1 compare"><br>
<label for="fname2">Test 3 : </label><input type="text" title="Test 3" id="fname2" class="form1 compare"><br>
<label for="gender">Gender : </label>
<input type="radio" title="Male" id="fname3" class="gender" name="gender" value="Male"><label for="gender">Male</label>
<input type="radio" title="Female" id="fname4" class="gender" name="gender" value="Female"><label for="gender">Female</label><br>
<label for="fname5">Mobile : </label><input type="text" title="Mobile" id="fname5" class="numeric"><br>
<label for="fname6">Email : </label><input type="text" title="Email" id="fname6" class="email"><br>
<input type="submit" id="sub" value="Submit">
</form>
</body>
</html>
function hasValue( val ) { // Return true if text input is valid/ not-empty
return val.replace(/\s+/, '').length; // boolean
}
For multiple elements you can pass inside your input elements loop their value into that function argument.
If a user inserted one or more spaces, thanks to the regex s+ the function will return false.
<pre><form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form></pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.js js file
For flexibility and other places you might want to validated. You can use the following function.
`function validateOnlyTextField(element) {
var str = element.value;
if(!(/^[a-zA-Z, ]+$/.test(str))){
// console.log('String contain number characters');
str = str.substr(0, str.length -1);
element.value = str;
}
}`
Then on your html section use the following event.
<input type="text" id="names" onkeyup="validateOnlyTextField(this)" />
You can always reuse the function.
i'm trying to make sure certain fields are not left blank in my form. it seems simple enough but for some reason it's not working. The alert is not showing, and return false is not working (it continues to post blank entries into my database) please help, what am i doing wrong. thank you!
the script:
function check(){
var name = getElementById('name');
var date = getElementById('date');
var pri = getElementById('pri');
var asapc = getElementById('asapc');
var asapn = getElementById('asapn');
var obr = getElementById('obr');
var obc = getElementById('obc');
var obn = getElementById('obn');
if (name.value == "" || date.value == "" || pri.value == "not" || asapc.value == "" || asapn.value == "" || obr.value == "" || obc.value == "" || obn.value == "") {
alert( "One or more fields were not filled out." );
return false ; }
return true;
}
The code:
<FORM ACTION="step2.php" METHOD="POST" onsubmit="check();">
<!-- fields here -->
<INPUT TYPE="submit" VALUE="CONTINUE">
access every element as document.getElementById... and in form tag write this onsubmit="return check();" instead if onsubmit="check();"
You are missing return here:
<FORM ACTION="step2.php" METHOD="POST" onsubmit="return check();">
You are missing (document) this is the correct syntax:
document.getElementById('id');
<script>
function check() {
var name = document.getElementById('name');
var date = document.getElementById('date');
if (name.value == "" || date.value == "") {
alert( "One or more fields were not filled out.");
return false;
}
}
</script>
and getElementByID means by ID not my tagName
<FORM ACTION="step2.php" METHOD="POST" onsubmit="return check();">
<input name="name" type="text" value="" id="name">
<input name="date" type="text" value="" id="date">
.....etc..
<INPUT TYPE="submit" VALUE="CONTINUE">
</FORM>
This phone number validator doesn't work :/. Why?
Ideally, if the optional phone field is not null, it should proceed to validate the form.
The phone field is optional, and isn't required.
Validating the form:
the phone field is optional. this means that it is not required.
it should ignore comparing everything except numbers.
if the digit count is != 10 numbers, it should display the error.
if the count is equal to 10 digits, it should pass onto name.php (see the HTML)
Javascript Code:
function validateForm() {
var x=document.forms["form"]["name"].value;
if (x==null || x=="")
{
alert("Name is required.");
return false;
}
var y=document.forms["form"]["email"].value;
var atpos=y.indexOf("#");
var dotpos=y.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=y.length)
{
alert("Valid email required.");
return false;
}
var formValue = document.forms["form"]["number"].value;
var regExpressionValue = /[^\d.]/g;
if (formValue !== null)
{
if (regExpressionValue.test(formValue) !== true)
{
alert("Optional phone number invalid. Example: [1234567890].");
return false;
}
}
return true;
}
HTML:
<form class="form" id="form" name="form" method="post" action="name.php" onsubmit="return validateForm()" />
<input type="text" name="name" id="name" />
<input type="text" name="email" id="email" />
<input type="tel" name="number" id="number" />
<button type="submit" value="Send" />Sign Up</button>
<div class="spacer"></div>
</form>
Your regular expression is wrong. Try this instead
if (/^\d{10}$/.test(formValue) === false) {
alert("Optional phone number invalid. Example: [1234567890].");
return false;
}
You have bad regexp and string presence check for phone number. Check this out:
function validateForm() {
var x=document.forms["form"]["name"].value;
if (x==null || x=="")
{
alert("Name is required.");
return false;
}
var y=document.forms["form"]["email"].value;
var atpos=y.indexOf("#");
var dotpos=y.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=y.length)
{
alert("Valid email required.");
return false;
}
var formValue = document.forms["form"]["number"].value;
if (formValue)
{
var regExpressionValue = /^(\d-?){10}$/g;
if (regExpressionValue.test(formValue) !== true)
{
alert("Optional phone number invalid. Example: [1234567890].");
return false;
}
}
return true;
}