Two fields validation - javascript

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

Related

Javascript form validation only working once

Script: NewsletterScript.js
function formValidation() {
var fname = document.getElementById('firstName').value;
var lname = document.getElementById('lastName').value;
var pnumber = document.getElementById('phoneNumber').value;
var email = document.getElementById('e-mail').value;
if (FirstName(fname)) {
}
if (LastName(lname)) {
}
if (Country(country)) {
}
if (Email(email)) {
}
return false;
}
/*first name input validation*/
function FirstName(fname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( fname =="" || fname.match(letters)) {
text="";
message[0].innerHTML = text;
return true;
}
else {
text="First name should contain only letters";
message[0].innerHTML = text;
return false;
}
}
/*last name input validation*/
function LastName(lname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( lname =="" || lname.match(letters)) {
text="";
message[1].innerHTML = text;
return true;
}
else {
text="Last name should contain only letters";
message[1].innerHTML = text;
return false;
}
}
I'm trying to get this validation to loop until the criteria is fulfilled, currently this is only working once and if the button is clicked again it submits regardless. Button below.
Due to the script being so long its not letting me upload all of it, however its just got other validation such as phone number etc, Any help will be appreciated, cheers!
If what you want is that formValidation() returns true only when the four validation functions return true you sould write that instead of putting empty if statements :
return FirstName(fname) && LastName(lname) && Country(country) && Email(email);
This manner formValidation() will return false if one of them return false
You should consider using form onsubmit instead on the onclick on the submit button.
Instead of:
<input class="button" type="submit" value="Submit" name="submit" onClick="formValidation()" />
consider using the form submit and do not forget the return keyword:
<form onsubmit="return formValidation();" > /* ... */ </form>
Related Question: HTML form action and onsubmit issues

How to Trigger Validation

How do I force a user to enter a valid time and valid number before pressing the button "Show"?
I have two fields in my html code and I found two good validation scripts in JS. One for time and one to determine if input field has a numeric value.
I can't change anything in the HTML.
function checkTime() {
re = /^\d{1,2}:\d{2}([ap]m)?$/;
if (time_untilopt.value != '' && !time_untilopt.value.match(re)) {
alert("Wrong time!");
return false;
}
}
function checkRoomNr() {
var numbers = /^[0-9]+$/;
if (roomopt.value.match(numbers)) {
console.log("is number");
} else {
console.log("not a number!");
}
}
<div>
<label for="time-until">Time</label>
<input type="text" id="time-until">
</div>
<div>
<label for="room">Room</label>
<input type="text" id="room">
</div>
<button id="show-schedule">Show</button>
If you want the validation to take place as data is being entered into the fields, you should set your functions up to run on the input event of the fields. If you want to wait until the user leaves the field and has made changes to the value of the field, then you can use the change event of the fields.
But, you'll also want the data to be checked when the form that contains the fields is submitted, so you need to set up a submit event handler for the form as well.
The way to connect a function to an event is to register the function as an "event handler" and that is done (using modern standards-based code) with the .addEventListener() method:
// First, get references to the elements you'll want to work with.
// And, use those variable names to reference the elements in your
// code, not their IDs.
var timeUntil = document.getElementById("time-until");
var room = document.getElementById("room");
var form = document.querySelector("form");
// We'll set up a variable to keep track of whether there are any errors
// and we'll assume that there are not any initially
var valid = true;
// Set up the event handling functions:
timeUntil.addEventListener("change", checkTime);
room.addEventListener("change", checkRoomNr);
form.addEventListener("submit", validate);
function checkTime(evt){
re = /^\d{1,2}:\d{2}([ap]m)?$/;
if(timeUntil.value != '' && !timeUntil.value.match(re)) {
console.log("Wrong time!");
valid = false; // Indicate an error
} else {
valid = true;
}
}
function checkRoomNr(evt){
var numbers = /^[0-9]+$/;
if(!room.value.match(numbers)){
console.log ("not a number!");
valid = false; // Indicate an error
} else {
valid = true;
}
}
// This function is called when the form is submitted
function validate(evt){
// Invoke the validation functions in case the fields have not been checked yet
checkTime();
checkRoomNr();
if(!valid){
evt.preventDefault(); // Cancel the form's submission
console.log("Submission cancelled due to invalid data");
}
}
<form action="#">
<div>
<label for="time-until">Time</label>
<input type="text" id="time-until">
</div>
<div>
<label for="room">Room</label>
<input type="text" id="room">
<div>
<button id="show-schedule">Show</button>
<form>
function checkTime( val ) { //Pass a value
return /^\d{1,2}:\d{2}([ap]m)?$/.test( val ); //Return a boolean
}
function checkNum( val ) { //Pass a value
return /^\d+$/.test( val ); //Return a boolean
}
const time = document.getElementById("time-until"),
room = document.getElementById("room"),
show = document.getElementById("show-schedule");
function validateForm () {
show.disabled = (checkTime( time.value ) && checkNum( room.value )) === false;
}
[time, room].forEach( el => el.addEventListener("input", validateForm) );
<div>
<label for="time-until">Time</label>
<input type="text" id="time-until">
</div>
<div>
<label for="room">Room</label>
<input type="text" id="room">
</div>
<!-- MAKE BUTTON DISABLED -->
<button id="show-schedule" disabled>Show</button>
Now you can reuse your functions like checkTime( val ) regardless of the input ID.
This may be a starting point basically you need to add event handlers and wire up time_untiloptand time_untilopt and add disabled to the show button. and listen for changes. There many ways, this is just an idea.
const button = document.getElementById('show-schedule');
const time_untilopt = document.getElementById('time-until');
const roomopt = document.getElementById('room');
function checkTime() {
re = /^\d{1,2}:\d{2}([ap]m)?$/;
if (time_untilopt.value != '' && !time_untilopt.value.match(re)) {
alert("Wrong time!");
return false;
}
return true;
}
function checkRoomNr() {
var numbers = /^[0-9]+$/;
if (roomopt.value.match(numbers)) {
console.log("is number");
return true;
} else {
console.log("not a number!");
return false;
}
}
function change() {
button.disabled = !(checkTime() && checkRoomNr());
}
<div>
<label for="time-until">Time</label>
<input type="text" id="time-until" onchange="change()">
</div>
<div>
<label for="room">Room</label>
<input type="text" id="room" onchange="change()">
</div>
<button id="show-schedule" disabled="true">Show</button>
Inside both of your functions you'll want to set up your variables (time_untilopt and roomopt) to actually point to your two <input> fields. Then you'll simply want to return true if they pass validation, and return false if they don't.
To trigger these checks, you'll want to set up an onlick attribute for your submission, which is tied in to a third function, which I have named show(). This third function should conditionally check that both of the other functions return true. If they do, all is good, and you can continue with the submission. If they're not good, simply return false in this function as well.
This can be seen in the following:
function checkTime() {
re = /^\d{1,2}:\d{2}([ap]m)?$/;
var time_untilopt = document.getElementById('time-until');
if (time_untilopt.value != '' && !time_untilopt.value.match(re)) {
return true;
}
else {
console.log("Wrong time!");
return false;
}
}
function checkRoomNr() {
var numbers = /^[0-9]+$/;
var roomopt = document.getElementById('room');
if (roomopt.value.match(numbers)) {
return true;
} else {
console.log("The room number is not a number!");
return false;
}
}
function show() {
if (checkTime() && checkRoomNr()) {
console.log('Both validations passed!');
return true;
}
else {
return false;
}
}
<div>
<label for="time-until">Time</label>
<input type="text" id="time-until">
</div>
<div>
<label for="room">Room</label>
<input type="text" id="room">
</div>
<button id="show-schedule" onclick="show()">Show</button>
Also note that your checkTime() function is actually doing the exact opposite of what you want; if the time is not empty and matches the validation, you want to return true, not false. This has been corrected in the above example.
Hope this helps! :)

Check the length of the number entered in a textbox

I want to write in text box and check if is integer and less than 16 numbers. I have the following JavaScript codes.
<script type="text/javascript">
function doCheck(field) {
if (isNaN(document.getElementById(field).value)) {
alert('this is not a number');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
else {
return true;
}
}
</script>
<form method="post" action="" onsubmit="return doCheck('number');">
national id=<input type="text" name="nat" id="number">
<input type="submit" name="submit">
</form>
document.getElementById(field).value.length
you can find the length of string inside the text box using this
function doCheck(field) {
var len = document.getElementById("number").val().length;
if(parse.Int(document.getElementById(field).value) && len < 16) {
return true;
}
else {
alert('your alert');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
}
be sure you parse it as an integer.
function doCheck(field) {
var input_value = document.getElementById(field).value;
if(isNaN(input_value) || parseInt(input_value,10) != input_value || input_value.length < 16) {
alert('this is not a number');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
else{
return true;
}
}
isNAN() checks whether a number is an illegal number of any type, not only integer. So you have to use something else there, a regular expressions maybe.
To get the length of the field you can simply use:
document.getElementById(field).value.length

How to alert user for blank form fields?

I have this form that has 3 inputs and when a user leaves a field blank a dialogue box pops up to alert the user a field is blank. The code I have below only works for 2 specific input. When i try adding another input to the code it doesnt work. It only works for 2 inputs. How can I make it work for all three?
<script type="text/javascript">
function val(){
var missingFields = false;
var strFields = "";
var mileage=document.getElementById("mile").value;
var location=document.getElementById("loc").value;
if(mileage=='' || isNaN(mileage))
{
missingFields = true;
strFields += " Your Google Map's mileage\n";
}
if(location=='' )
{
missingFields = true;
strFields += " Your business name\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
</script>
Showing 3 alerts may be disturbing, use something like this:
$(document).on('submit', 'form', function () {
var empty = $(this).find('input[type=text]').filter(function() {
return $.trim(this.value) === "";
});
if(empty.length) {
alert('Please fill in all the fields');
return false;
}
});
Inspired by this post.
Or you can do validation for each field this way using HTML data attributes:
<form data-alert="You must provide:" action="" method="post">
<input type="text" id="one" data-alert="Your Google Map's mileage" />
<input type="text" id="two" data-alert="Your business name" />
<input type="submit" value="Submit" />
</form>
... combined with jQuery:
$('form').on('submit', function () {
var thisForm = $(this);
var thisAlert = thisForm.data('alert');
var canSubmit = true;
thisForm.find('input[type=text]').each(function(i) {
var thisInput = $(this);
if ( !$.trim(thisInput.val()) ) {
thisAlert += '\n' + thisInput.data('alert');
canSubmit = false;
};
});
if( !canSubmit ) {
alert( thisAlert );
return false;
}
});
Take a look at this script in action.
Of course, you can select/check only input elements that have attribute data-alert (which means they are required). Example with mixed input elements.
You can add the required tag in the input fields. No jQuery needed.
<input required type="text" name="name"/>
Try this
var fields = ["a", "b", "c"]; // "a" is your "mile"
var empties= [];
for(var i=0; i<fields.length; i++)
{
if(!$('#'+fields[i]).val().trim())
empties.push(fields[i]);
}
if(empties.length)
{
alert('you must enter the following fields '+empties.join(', '));
return false;
}
else
return true;
instead of this
var name = $('#mile').val();
if (!name.trim()) {
alert('you must enter in your mile');
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