JavaScript validation for multiple functions? - javascript

I have a JavaScript function for a form. The code is :
<script type="text/javascript">
function verify() {
if (isNaN(document.form1.exp_amount.value) == true) {
alert("Invalid Block Amount");
return false;
} else if ((document.form1.exp_name.value).length == 0) {
alert("Block Exp is left Blank!");
return false;
} else if ((document.form1.exp_amount.value).length == 0) {
alert("Block Amount is left Blank!");
return false;
} else {
document.form1.submit();
return true;
}
}
</script>
Now I have to provide Alphabet Validation for it, which I have it in a separate JS function:
<script language="javascript" >
function checkName() {
re = /^[A-Za-z]+$/;
if (re.test(document.exp_name.form1.value)) {
alert('Valid Name.');
} else {
alert('Invalid Name.');
}
}
</script>
If I want to have Alphabet validation inside function verify(), how could I do it? Are there any other ways?

Please change your validation and form to this which will allow submission of the form if valid and not if errors. The following code is in my opinion canonical and will work on all browsers that support regular expressions (which was introduced in JS1.1 in 1996 with NS3.0) - please note that javascript does not support dashes in names unless you quote the field name in the script. The code does not need the form to be named since it passes the form object in the call (this) and uses the object in the function as theForm
<html>
<head>
<title>Canonical forms validation without jQuery</title>
<script type="text/javascript">
var validName = /^[A-Za-z]+$/;
function checkName(str) {
return validName.test(str);
}
function verify(theForm) {
// note: theForm["..."] is short for theForm.elements["..."];
var amount = theForm["exp_amount"].value;
if(amount ==""){
alert("Block Amount is left blank");
theForm["exp_amount"].focus();
return false;
}
if (isNaN(amount)) {
alert("Invalid Block Amount");
theForm["exp_amount"].focus();
return false;
}
var name = theForm["exp_name"].value;
if(name.length==0) {
alert("Block Exp is left Blank!");
theForm["exp_name"].focus();
return false;
}
if(!checkName(name)) {
alert("Block Exp is invalid!");
theForm["exp_name"].focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return verify(this)">
Amount: <input type="text" name="exp_amount" value="" /><br />
Name: <input type="text" name="exp_name" value="" /><br />
<input type="submit" />
</form>
</body>
</html>

Simply return false or true inside your checkName function:
function checkName()
{
re = /^[A-Za-z]+$/;
if(re.test(document.exp_name.form1.value))
{
alert('Valid Name.');
return true;
}
else
{
alert('Invalid Name.');
false;
}
}
Then call it and check the result.
...
else if((document.form1.exp_amount.value).length==0)
{
alert("Block Amount is left Blank!");
return false;
}
else if (!checkName()) {
return false;
}
else
{
document.form1.submit();
return true;
}
As an aside, there are many ways your code can be cleaned up and improved. I don't want to get into them now, but if you'd like to discuss it, just leave a comment.

Edit your checkName() function to
function checkName()
{
re = /^[A-Za-z]+$/;
if(re.test(document.exp_name.form1.value))
{
alert('Valid Name.');
return true;
}
else
{
alert('Invalid Name.');
return false;
}
}
And add
else if(!checkName()){ return false;}
to your validation code just before the form submit

<script type="text/javascript">
function verify()
{
if(isNaN(document.form1.exp_amount.value)==true)
{
alert("Invalid Block Amount");
return false;
}
else if((document.form1.exp_name.value).length==0)
{
alert("Block Exp is left Blank!");
return false;
}
else if((document.form1.exp_amount.value).length==0)
{
alert("Block Amount is left Blank!");
return false;
}
else if(!(/^[A-Za-z]+$/.test(document.form1.exp_amount.value))) //ADD THIS
{
alert('Invalid Name');
return false;
}
document.form1.submit();
return true;
}
</script>

Related

Why Javascript validation is not working in html form?

When i try name box is fill with character it always show that "Name must be in character only.".
Here is Javascript code:
function validate_form() {
if (!(/^[A-Za-z]+$/).test(document.emp.new_name.value)) {
alert("Name must be in character only.");
return false;
}
if (!(/^\d{10}$/).test(document.emp.new_number.value)) {
alert("Enter valid mobile number");
return false;
}
if (!(/^[0-9.]+$/).test(document.emp.new_salary.value)) {
alert("salary must be numeric");
return false;
}
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(document.emp.new_email.value)) {
alert("You have entered an invalid email address!")
return (false);
}
alert ("success");
return true;
}
Because initially it does not have any characters, try adding a check to character length
Checkout example
$("#submit").on("click",function(){
var name = $("#name").val();
if (name.length>0 && !(/^[A-Za-z]+$/).test(name)) {
alert("Name must be in character only.");
return false;
}
else{
alert("ok");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name"><input type="submit" id="submit">
var name = document.emp.new_name.value;
if (name.value.search(/[^a-zA-Z]+/) === -1) {
alert("Name must be in character only.");
return false;
}
Try with this code. Hopefully, this will work.

Form validation script before submission

There is a form, where on submission the new page is opened, only in case if validation is ok. However, the window is opened in every case, and I guess that validation isnt working, while it is supposed to...
I would appreciate if you could point me to the right direction.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function overallcheck() {
if (!checkjob() || !checkEmail() || !Checkname()) {
writeTo("problemArea", "Error messages area");
return false;
}
if (!Checkname()) {
writeTo("problemArea", "Please inser a valid name");
return false;
}
if (!checkEmail()) {
writeTo("problemArea", "Please inser a valid email");
return false;
}
if (!checkjob()) {
writeTo("problemArea", "Please inser your job");
return false;
}
elsereturn true;
}
function Checkname() {
clearElement("problemArea");
var fullname = document.forms['form'].fullname.value;
if (fullname.length == 0 || !isNaN(fullname))
return false;
}
function checkEmail() {
clearElement("problemArea");
var mail = document.forms['form'].Email.value;
if (mail == '' || mail.indexOf('#') == -1 || mail.indexOf('.') == -1)
return false;
}
}
function checkjob() {
clearElement("problemArea");
var i;
for (i = 0; i < 4; i++) {
if (document.forms['form'].job[i].checked) {
return true;
}
}
return false;
}
//-->
</script>
</head>
<body>
<form onsubmit=( "return overallcheck();") action="another.html" id=form target="_blank" method="GET">
<table>
<button type="submit" onclick="">submit</button>
</form>
</body>
</html>
Well... That's invalid JavaScript. As NewToJS noted in his comment, elsereturn true; is not correct.
You need to use:
else {
return true;
}
Also, this (onsubmit=( "return overallcheck();")) won't work. You need to do this:
<form onsubmit="return overallcheck();" action="another.html" id="form" target="_blank" method="GET">

Should I validate my form twice?

My code works perfectly here.
But the problem is that I want to add some code validation so that the form can't be submitted if something is wrong in the code. Here is the code I added:
Jquery code:
var user = document.getElementById('u');
var email = document.getElementById('em');
var pass1 = document.getElementById('p1');
var pass2 = document.getElementById('pa2');
function isEmpty(input) {
if (input.value == "" || input.value == null) {
return true;
} else {
return false;
}
}
function validateform() {
if(isEmpty(user) || isEmpty(email) || isEmpty(pass1) || isEmpty(pass2))
{
alert("All fields are required.");
$("#form").submit(function(event) {
event.preventDefault();
});
if(isEmpty(user))
{
user.focus();
}
else if(isEmpty(email))
{
email.focus();
}
else if(isEmpty(pass1))
{
pass1.focus();
}
else if(isEmpty(pass2))
{
pass2.focus();
}
}
}
I also added an Id to my form:
<form action="m.php" method="post" id="form">
I also added the onsubmit here:
<input name="submit" type='submit' value='Submit' onsubmit="validateform()">
but it is not working, the page just moves to m.php even if all fields are empty. what should I do? should I install the jquery validating plugin and validate twice?
Edit
Here is a Demo
After you check if the field is empty if you return false; then the from will not submit.
Form on submit example.
JavaScript
function validateform() {
if(isEmpty(user))
{
user.focus();
return false;
}
else if(isEmpty(email))
{
email.focus();
return false;
}
else if(isEmpty(pass1))
{
pass1.focus();
return false;
}
else if(isEmpty(pass2))
{
pass2.focus();
return false;
}
}
Your onsubmit needs to be on your form not your button.
HTML
<form action="m.php" method="post" id="form" onsubmit="validateform()">
<input name="submit" type='submit' value='Submit' >
Don't need to validate twice.
JS:
function isEmpty(input) {
return $.trim(input.value) == "";
}
function validateform() {
var user = document.getElementById('u');
var email = document.getElementById('em');
var pass1 = document.getElementById('p1');
var pass2 = document.getElementById('pa2');
if(isEmpty(user) || isEmpty(email) || isEmpty(pass1) || isEmpty(pass2))
alert("All fields are required.");
if(isEmpty(user)){
user.focus();
return false;
}else if(isEmpty(email)){
email.focus();
return false;
}else if(isEmpty(pass1)){
pass1.focus();
return false;
}else if(isEmpty(pass2)){
pass2.focus();
return false;
}
return true;
}
$('form#myForm').submit(function(e){
e.preventDefault();
if( validateform() ) //just validate once!
this.submit(); //and then submit once;
return false;
});
HTML:
<form action="m.php" method="post" id="myForm">
.....
......Other form settings....
.....
<input name="submit" type='submit' value='Submit'>
</form>

Two fields validation

<html>
<head>
</head>
<body>
<form class="form-horizontal cmxform" id="validateForm" method="get" action="../../course_controller" onsubmit="return validate();" autocomplete="off">
<input type="text" id="course_name" name="course_name" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:return validate_course_name();">
<label id="course_name_info" style="color:rgba(255,255,255,0.6);font-size:13px">
</label>
<input type="text" id="course_desc" name="course_desc" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:return validate_course_desc();">
<label id="course_desc_info" style="color:rgba(255,255,255,0.6);font-size:13px">
</label>
<button type="submit" name="user_action" value="add" class="btn btn-primary" >Save</button>
<button type="reset" class="btn btn-secondary">Cancel</button>
</form>
<script type="text/javascript">
/**** Specific JS for this page ****/
//Validation things
function validate_course_name(){
var TCode = document.getElementById('course_name').value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return true;
}
}
function validate_course_desc(){
var TCode = document.getElementById('course_desc').value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById('course_desc_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
document.getElementById('course_desc_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return true;
}
}
function validate(){
return validate_course_name();
return validate_course_desc();
}
</script>
</body>
</html>
So this the code ...I am applying alpha numeric validation on two field but the problem is if i give first input field valid input and second invalid form get submitted where am i doing it wrong? ...i am very new to this web so any help will be appreciated:)
UPDATED ANSWER:
Fine! Just to be different =)
One line, should validate both fields regardless if the validate_course_name() returns false.
JSFiddle: http://jsfiddle.net/fVqTY/3/
function validate()
{
return (validate_course_name() * validate_course_desc()) == true;
}
Let false = 0, true = 1. Now do the math :)
function validate(){
var value1 = validate_course_name();
var value2 = validate_course_desc();
if(value1 == true && value2 == true)
return true;
else
return false
}
or You can use
function validate(){
var validate = true;
var TCode = document.getElementById('course_name').value;
var TCode1 = document.getElementById('course_desc').value;
if(! /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
validate = false;
}
if(! /[^a-zA-Z1-9 _-]/.test( TCode1 ) ) {
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
validate = false;
}
return validate;
}
and then call this function directly
In this function, You should return only once. So what happens here is that when validate_course_name() gets executed, control is already returned to the calling routine. validate_course_desc() line won't execute.
function validate(){
return validate_course_name();
return validate_course_desc();
}
You should do this:
function validate(){
var bol1 = validate_course_name();
var bol2 = validate_course_desc();
if(bol1 == true && bol2 == true)
return true;
else
return false;
}
Your validate method as given below will return as soon as the first validate method (validate_course_name) is called so it will not execute the validate_course_desc method.
function validate(){
return validate_course_name();
return validate_course_desc();
}
The solution is to execute both the validate method and summarise them to create the return value as given in the above answers
change the function validate()
function validate()
{
if(validate_course_name() && validate_course_desc())
{
return true;
}
return false;
}
Once return statement is executed in a function, other statements that are following return statement does not work.
Therefore every time, validate_course_name() function is called , a bool value is returned and the function validate_course_desc() is not even called/executed.
Therefore, the validate function returns true if validate_course_name() is true and false if validate_course_name() return false.Hence , When you give first field valid input and second invalid, form get submitted.
the validation of both inputfields is the same, so you can make one validation function which takes an element-id as parameter:
function validateInputfield(id){
var TCode = document.getElementById(id).value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById(id).innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
} else {
return true;
}
}
Then you can use the function validate() to check if both inputfields are valid:
function validate() {
if (validateInputfield('course_desc_info') == true &&
validateInputfield('course_name_info') == true) {
return true;
} else {
return false;
}
}

Javascript validation not working?

What's wrong in it why it's not working...
<script language="JavaScript" type="text/javascript">
//function to check empty fields
function isEmpty(strfield1, strfield2) {
//change "field1, field2 and field3" to your field names
strfield1 = document.forms[0].name.value
strfield2 = document.forms[0].email.value
//name field
if (strfield1 == "" || strfield1 == null || !isNaN(strfield1) || strfield1.charAt(0) == ' ') {
alert( "Name is a mandatory field.\nPlease amend and retry.")
return false;
}
//EMAIL field
if (strfield2 == "" || strfield2 == null || !isNaN(strfield2) || strfield2.charAt(0) == ' ') {
alert(" Email is a mandatory field.\nPlease amend and retry.")
return false;
}
return true;
}
//function to check valid email address
function isValidEmail(strEmail){
validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
strEmail = document.forms[0].email.value;
// search email text for regular exp matches
if (strEmail.search(validRegExp) == -1) {
alert('A valid e-mail address is required.\nPlease amend and retry');
return false;
}
return true;
}
//function that performs all functions, defined in the onsubmit event handler
function check(form)){
if (isEmpty(form.field1)){
if (isEmpty(form.field2)){
if (isValidEmail(form.email)){
return true;
}
}
}
}
return false;
}
</script>
It doesn't do anything I don't understand what's going there and in form I put this too
<form onsubmit="return check(this);" action="sendquery.php" name="contquery">
First glance: too many brackets as shown by #FishBasketGordo so I will not repeat
Second glance - you pass the field and do not test the field value
Third glance: You do not pass the correct names to the function
Fourth glance - isEmpty returns false when empty. It should return true
I fixed all those
DEMO HERE
Complete page to show where what goes. Updated to do unobtrusive event handling on the form
<html>
<head>
<title>Validation</title>
<script type="text/javascript">
// trim for IE
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
//function to check empty fields
function isEmpty(objfld) {
var val = objfld.value;
if (val.trim() == "" || val == null) {
alert(objfld.name+" is a mandatory field.\nPlease amend and retry.");
objfld.focus();
return true;
}
return false;
}
//function to check valid email address
function isValidEmail(objEmail){
var validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
var strEmail = objEmail.value;
if (strEmail.match(validRegExp)) return true;
alert('A valid e-mail address is required.\nPlease amend and retry');
objEmail.focus();
return false;
}
//function that performs all functions, defined in the onsubmit event handler
function validate(form) {
if (isEmpty(form.name)) return false;
if (isEmpty(form.email)) return false;
return isValidEmail(form.email);
}
window.onload=function() {
document.getElementById("form1").onsubmit=function() {
return validate(this);
}
}
</head>
<body>
<form id="form1">
Name:<input type="text" name="name" /><br/>
Email:<input type="text" name="email" /><br/>
<input type="submit" />
</form>
</body>
</html>
Probably the main reason it isn't working is the syntax errors:
// Syntax error ----v
function check(form)){
if (isEmpty(form.field1)){
if (isEmpty(form.field2)){
if (isValidEmail(form.email)){
return true;
}
}
}
}
// The return statement should be above the previous closing bracket
// and the final closing bracket removed.
return false;
}
There's an extra closing paren on the first line, and there are too many closing brackets. If you open up this up in FireBug or Chrome Developer Tools or a similar tool, it would tell you about this automatically.

Categories

Resources