JavaScript Validation error message is not disappearing after I click submit - javascript

The code below validates a form with two fields. When I click the submit button without any data the error messages would show which is working fine but if I input data after and click submit button the error message doesn't disappear.
<script>
function validateForm() {
var valid = true;
var x = document.forms["myForm"]["activityName"].value;
if (x == "" || x == null) {
document.getElementById("activityName").innerHTML = "Please Enter Activity Name";
valid= false;
}
var r = document.forms["myForm"]["reporter"].value;
if (r == "") {
document.getElementById("reporter").innerHTML = "Please Enter Reporter";
valid = false;
}
return valid;
}
</script>
</head>
<body>
<form action="#" method="post" name="myForm" onsubmit=" return validateForm()">
<div>
<label for="myActivityName">*Activity Name:</label>
<input type="text" name="activityName" value="" placeholder="Enter Activity Name" />
<p id="activityName"></p>
</div><br>
<div>
<label for="reporter">*Reporter:</label>
<input type="text" name="reporter" value="" placeholder="Enter Reporter " />
<p id="reporter"></p>
</div><br>
<input type="submit" value="Submit" >
</form>
</body>

The other answer is right, but here is some code to back it up with. Notice that the innerHTML of both activityName and reporter get (re)set back to empty before the validation occurs:
function validateForm() {
var valid = true;
document.getElementById("activityName").innerHTML = "";
document.getElementById("reporter").innerHTML = "";
var x = document.forms["myForm"]["activityName"].value;
if (x == "" || x == null) {
document.getElementById("activityName").innerHTML = "Please Enter Activity Name";
valid= false;
}
var r = document.forms["myForm"]["reporter"].value;
if (r == "") {
document.getElementById("reporter").innerHTML = "Please Enter Reporter";
valid = false;
}
return valid;
}

Your problem is you never "unvalidate" the form a.k.a. remove the previous validation errors. Before you return from validation, if there were no errors, just revert your validation checks. This will ensure it will "clean" your interface if nothing is wrong.

Related

JS Function is invoked but no result

When I invoke the function it is getting invoked but it flashes the result. Could please tell me what is the mistake I did?
Below is the HTML Code I used:
I have replaced the input type as a button but still, error not fixed.
function reg() {
//Name Field
var f = document.forms["registration"]["fullname"].value;
if (f == "") {
alert("Enter the name");
return false;
} else if (!f.match(/^.[a-zA-Z]+$/))
{
alert("Enter only alphabets");
return false;
}
document.getElementById('details').innerHTML = "Hi" + registration.fullname.value;
}
<form name="registration" onsubmit="return reg()">
<input type="text" name="fullname" placeholder="Enter Your Full Name"><br><br>
<input type="submit" value="submit">
</form>
Here is what I believe you want to do.
Note it is better to add an event handler in the script rather than having an inline handler, but for now I pass the form itself in the function
function reg(form) {
//Name Field
var f = form.fullname.value;
if (f == "") {
alert("Enter the name");
return false;
}
// no need for else when you return
if (!f.match(/^[\. a-zA-Z]+$/)) { // I personally have a space in my full name
alert("Enter only alphabets and space");
return false;
}
document.getElementById('details').innerHTML = "Hi " + f;
// change to true if you want to submit the form but you will then not be able to see the HI
return false;
}
<form name="registration" onsubmit="return reg(this)">
<input type="text" name="fullname" placeholder="Enter Your Full Name"><br><br>
<input type="submit" value="submit">
</form>
<span id="details"></span>

Text obtained with innerHTML dissapear

I have the following code:
function passVerif() {
if (document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
if (document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="button" name="required" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
As you can see, input type is submit. Because of that (page is refreshing after click on button) the text I want to show disappears after refresh.
As I read on other posts, the simple change from submit to button will do the dew.
But I am suspecting that I messed up the return false and return true instructions in all of my functions.
Is this correct? If they are in a logical way I can avoid the page refresh and continue to use submit? At least until all conditions are met and the form is good to go.
In other words, can someone help me to put return false and true in such way that the page will refresh only if all conditions are met.
Thanks a lot, I am not even a noob.
Codes are copied from different sources on the internet. I am at the very beginning of coding road. Please have mercy :)
I would change it to one validation function and have a bool that is returned based on if it has errored or not:
// Just have one validation function
function validate() {
var errorMessage = ''; // build up an error message
var email = document.forms['form'].email.value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (email === "") {
errorMessage += "Email field is empty!<br>";
} else if (!emailFilter.test(email)) { // this can be else if
errorMessage += "Please enter a valid e-mail address!<br>";
}
if (document.forms['form'].pass.value === "") {
errorMessage += "Password field is empty!<br>"
}
if (errorMessage === '') {
return true; // return true as no error message
} else {
document.getElementById('error-message').innerHTML = errorMessage; // show error message and return false
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="submit" name="required" onclick="return validate();">
</form>
</div>
<div id="error-message">
<!-- CAN HAVE ONE ERROR MESSAGE DIV -->
</div>
I tried with your code and I could find the the messages were not getting updated based on the conditions. So I did few modifications to your code to display the message based on which condition fails.
HTML
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br><br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br><br>
<input type="submit" name="required" value="Submit" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
JS
function passVerif() {
messagePV.innerHTML = ("")
if(document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
messageEV.innerHTML = ("")
if(document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
messageV.innerHTML = ("")
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
By initializing the errormessage filed to empty sting u can maintain the fresh set of error messages.
Jsfiddle: https://jsfiddle.net/85w7qaqx/1/
Hope this helps out.

Individual error messages for empty form fields using JavaScript

I need to validate my form using JavaScript because iPhone / Safari do not recognize the required attribute. I want individual error messages to appear below each empty input field.
My code works, but the individual error message does not disappear when the field is filled in. Also, I would like all messages to appear initially, for all empty fields (not one by one). I am very very new to JavaScript, sorry.
My HTML:
<form onsubmit="return validateForm()" method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
And my JavaScript:
<script>
function validateForm() {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").innerHTML = nameError;
return false;
}
else if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").innerHTML = emailError;
return false;
}
else if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").innerHTML = telephoneError;
return false;
}
else {return true;}
}
</script>
Thanks for your help.
Here is a solution that displays all relevant errors when the form is first submitted, and removes an error when the user modifies text in the relevant input element.
To get it to display all of the errors on first run, I used if statements instead of if else, and used a flag to determine whether the form should be submitted. To remove the warnings when the input is modified, I bound the onkeyup events of the inputs.
I ended up removing the required attributes on the inputs so that the demonstration will work in a modern browser that supports them.
Live Demo:
document.getElementById("english_registration_form").onsubmit = function () {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
var submit = true;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").innerHTML = nameError;
submit = false;
}
if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").innerHTML = emailError;
submit = false;
}
if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").innerHTML = telephoneError;
submit = false;
}
return submit;
}
function removeWarning() {
document.getElementById(this.id + "_error").innerHTML = "";
}
document.getElementById("name").onkeyup = removeWarning;
document.getElementById("email").onkeyup = removeWarning;
document.getElementById("telephone").onkeyup = removeWarning;
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" placeholder="Name"> <span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" placeholder="Email"> <span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" placeholder="Telephone"> <span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
JSFiddle Version: https://jsfiddle.net/xga2shec/
First of all, we change your function validateForm so it can handle multiple validations.
Then, we create a DOMContentLoaded event handler on the document, and we call the validateForm function, so we validate the field when the page is loaded.
And to finish, we create input event handlers on the inputs, so everytime someone change any data inside them, the form is validated again.
Take a look at the code commented, and see the working version in action!
function validateForm() {
var valid = true; // creates a boolean variable to return if the form's valid
if (!validateField(this, 'name')) // validates the name
valid = false;
if (!validateField(this, 'email')) // validates the email (look that we're not using else if)
valid = false;
if (!validateField(this, 'telephone')) // validates the telephone
valid = false;
return valid; // if all the fields are valid, this variable will be true
}
function validateField(context, fieldName) { // function to dynamically validates a field by its name
var field = document.forms['english_registration_form'][fieldName], // gets the field
msg = 'Please enter your ' + fieldName, // dynamic message
errorField = document.getElementById(fieldName + '_error'); // gets the error field
console.log(context);
// if the context is the form, it's because the Register Now button was clicked, if not, check the caller
if (context instanceof HTMLFormElement || context.id === fieldName)
errorField.innerHTML = (field.value === '') ? msg : '';
return field.value !== ''; // return if the field is fulfilled
}
document.addEventListener('DOMContentLoaded', function() { // when the DOM is ready
// add event handlers when changing the fields' value
document.getElementById('name').addEventListener('input', validateForm);
document.getElementById('email').addEventListener('input', validateForm);
document.getElementById('telephone').addEventListener('input', validateForm);
// add the event handler for the submit event
document.getElementById('english_registration_form').addEventListener('submit', validateForm);
});
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
you have to use style.display="none" to hide error
and style.display="block" to show error
<script>
function validateForm() {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").style.display="block";
document.getElementById("name_error").innerHTML = nameError;
return false;
}
else if (x != null || x != "") {
nameError = "Please enter your name";
document.getElementById("name_error").style.display="none";
return false;
}
if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").style.display="block";
document.getElementById("email_error").innerHTML = emailError;
return false;
}
else if (y != null || y != "") {
emailError = "Please enter your email";
document.getElementById("email_error").style.display="none";
return false;
}
if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").style.display="block";
document.getElementById("telephone_error").innerHTML = telephoneError;
return false;
}
else if (z != null || z != "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").style.display="none";
return false;
}
else {return true;}
}
</script>
function validateForm() {
var valid = true; // creates a boolean variable to return if the form's valid
if (!validateField(this, 'name')) // validates the name
valid = false;
if (!validateField(this, 'email')) // validates the email (look that we're not using else if)
valid = false;
if (!validateField(this, 'telephone')) // validates the telephone
valid = false;
return valid; // if all the fields are valid, this variable will be true
}
function validateField(context, fieldName) { // function to dynamically validates a field by its name
var field = document.forms['english_registration_form'][fieldName], // gets the field
msg = 'Please enter your ' + fieldName, // dynamic message
errorField = document.getElementById(fieldName + '_error'); // gets the error field
console.log(context);
// if the context is the form, it's because the Register Now button was clicked, if not, check the caller
if (context instanceof HTMLFormElement || context.id === fieldName)
errorField.innerHTML = (field.value === '') ? msg : '';
return field.value !== ''; // return if the field is fulfilled
}
document.addEventListener('DOMContentLoaded', function() { // when the DOM is ready
// add event handlers when changing the fields' value
document.getElementById('name').addEventListener('input', validateForm);
document.getElementById('email').addEventListener('input', validateForm);
document.getElementById('telephone').addEventListener('input', validateForm);
// add the event handler for the submit event
document.getElementById('english_registration_form').addEventListener('submit', validateForm);
});
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>

Uncaught ReferenceError: form is not defined

Can't for the life of me figure this out. any help would be greatly appreciated!
This is the message I receive in Google Chrome when I test the script:
Navigated to http://localhost/contact.php
form2.js:2 Uncaught ReferenceError: form is not definedform2.js:2 validatecontact.php:24 onsubmit
Navigated to http://localhost/contact.php
My contact.php file:
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="form2.js"></script>
<?php require 'Includes/Header.php'; ?>
<div class="wrapper">
<div id="contact-form">
<h5>Contact Form</h5>
<form name="contact" form method="post" action="contact.php"
onsubmit="return validate(contact)">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<label for="message">Message:</label>
<textarea id="message" name="message"></textarea>
<button type="submit">Submit</button>
</form>
<div class="clear"></div>
</div>
</div>
<?php require 'Includes/Footer.php'; ?>
My form2.js file:
function validate(contact){
var name = form.name.value;
var email = form.email.value;
var message = form.message.value;
if (name.length == 0 || name.length > 200)
{alert ("You must enter a name.");
return false;
}
if (email.length == 0 || email.length > 200)
{alert ("You must enter a email.");
return false;
}
if (message.length == 0)
{alert ("You must enter a message.");
return false;
}
return true;
}
form is a javascript object. That object does not exist within this file, which is why the error is being thrown. If you want to validate this form, you need to get a reference to it from the DOM first, using document.contact.
function validate(contact){
var form = document.contact,
name = form.name.value,
email = form.email.value,
message = form.message.value;
if (name.length == 0 || name.length > 200) {
alert ("You must enter a name.");
return false;
}
if (email.length == 0 || email.length > 200) {
alert ("You must enter a email.");
return false;
}
if (message.length == 0) {
alert ("You must enter a message.");
return false;
}
return true;
}
try using jquery by adding
<script type="text/javascript" charset="utf-8" src="./jquery-1.9.1.js" />
to the header (you will have to download it or then add:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
to get the latest)
then in your function get the values of the input fieds as follow:
var name = $('#name').value;
var email = $('#email').value;
var message = $('#message').value;
Access forms like this
<form action="#" name="test_form">
<input name="firstname" value="hello world"/>
</form>
var valueOfInput = document.test_form.firstname.value
you can also go like documents.forms["test_form"].elements
so maybe passing in document.contact can help ...
otherwise look at libraries like jQuery which give you a nice api to access DOM elements.
The error is what it says. You don't have a form variable defined (From what you've shared).
Also, it looks like you're trying to validate your form by accessing the values of the input fields. Here is how you should / could do it -
function validate(contact){
var name = document.getElementsByName('name')[0].value;
// You can also do the following
// var name = document.getElementById('name').value;
// var name = document.forms['contact'].elements['name'].value;
var email = document.getElementsByName('email')[0].value;
var message = document.getElementsByName('message')[0].value;
if (name.length == 0 || name.length > 200)
{
alert ("You must enter a name.");
return false;
}
if (email.length == 0 || email.length > 200)
{
alert ("You must enter a email.");
return false;
}
if (message.length == 0)
{
alert ("You must enter a message.");
return false;
}
return true;
}

validation of input text field in html using javascript

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

Categories

Resources