Data validation in javascript

JavaScript Form Validation – W3Schools

Data Validation. Data validation is the process of ensuring that user input is clean, correct, and useful. Typical validation tasks are: has the user filled in all required fields? has the user entered a valid date? has the user entered text in a numeric field? Most often, the purpose of data validation is to ensure correct user input.

Code sample

function validateForm() {  var x = document.forms[«myForm»][«fname»].value;  if (x == null || x == «») {    alert(«Name must be filled out»);      return false;See more on w3schoolsWas this helpful?Thanks! Give more feedback

JavaScript Form Validation – Tutorials Point

JavaScript provides a way to validate form’s data on the client’s computer before sending it to the web server. Form validation generally performs two functions. Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in.

How to Use JavaScript to Validate Form Data | WebReference

How to use JavaScript to validate important types of form data, including names, addresses, URLs, email addresses, phone numbers, zip codes, expiration dates, and credit card numbers (Visa, Master Card, Discover, and American Express, in both Canadian and American formats, with either 13, 14, 15, or 16 digit account numbers).

Effective Data Validation in JavaScript – medium.com

Effective Data Validation in JavaScript Introduction. Most applications will need to validate data at some point. This data might be provided by an external service or via user interaction or input.

Data validation with JavaScript and regular expressions

Data validation is an essential aspect of any Web application that accepts data from the user. After all, you must ensure the data is formatted as expected before working with it.

Data Validation: DevExtreme – HTML5 JavaScript UI Widgets

Data Validation This guide provides the detailed information on validation capabilities of DevExtreme editors. It describes how to validate a single editor or a group of editors, display the validation summary, perform remote validation, use a custom validation engine, etc.

JavaScript : Date validation – w3resource

Date validation. It is very important to validate the data supplied by the user through a form before you process it. Among various kind of data validation, validation of date is one. In this tutorial, we discussed how you can perform JavaScript date validation in 1. dd/mm/yyyy or dd-mm-yyyy format. 2. mm/dd/yyyy or mm-dd-yyyy format.

Form data validation – Learn web development | MDN

What Is Form Validation?

How to validate date with format «mm/dd/yyyy» in JavaScript?

Without any further details regarding the type of data that isn’t working, there isn’t much else to give input on.

I think Niklas has the right answer to your problem. Besides that, I think the following date validation function is a little bit easier to read: // Validates that the input string is a valid date formatted as «mm/dd/yyyy»
function isValidDate(dateString)
{
// First check for the pattern
if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))
return false;

// Parse the date parts to integers
var parts = dateString.split(«/»);
var day = parseInt(parts[1], 10);
var month = parseInt(parts[0], 10);
var year = parseInt(parts[2], 10);

// Check the ranges of month and year
if(year 3000 || month == 0 || month > 12)
return false;

var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

// Adjust for leap years
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
monthLength[1] = 29;

// Check the range of the day
return day > 0 && day <= monthLength[month – 1];
};144
I would use Moment.js for date validation. alert(moment(«05/22/2012», ‘MM/DD/YYYY’,true).isValid()); //true
Jsfiddle: http://jsfiddle.net/q8y9nbu5/71
Use the following regular expression to validate: var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;
if(!(date_regex.test(testDate)))
{
return false;
}
This is working for me for MM/dd/yyyy.31
All credits go to elian-ebbing Just for the lazy ones here I also provide a customized version of the function for the format yyyy-mm-dd . function isValidDate(dateString)
{
// First check for the pattern
var regex_date = /^\d{4}\-\d{1,2}\-\d{1,2}$/;

if(!regex_date.test(dateString))
{
return false;
}

// Parse the date parts to integers
var parts = dateString.split(«-«);
var day = parseInt(parts[2], 10);
var month = parseInt(parts[1], 10);
var year = parseInt(parts[0], 10);

// Check the ranges of month and year
if(year 3000 || month == 0 || month > 12)
{
return false;
}

var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

// Adjust for leap years
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
{
monthLength[1] = 29;
}

// Check the range of the day
return day > 0 && day <= monthLength[month – 1];
}23
It appears to be working fine for mm/dd/yyyy format dates, example: http://jsfiddle.net/niklasvh/xfrLm/ The only problem I had with your code was the fact that: var ExpiryDate = document.getElementById(‘ ExpiryDate’).value;
Had a space inside the brackets, before the element ID. Changed it to: var ExpiryDate = document.getElementById(‘ExpiryDate’).value;
Without any further details regarding the type of data that isn’t working, there isn’t much else to give input on.8
You could use Date.parse() You can read in MDN documentation The Date.parse() method parses a string representation of a date, and
returns the number of milliseconds since January 1, 1970, 00:00:00 UTC
or NaN if the string is unrecognized or, in some cases, contains
illegal date values (e.g. 2015-02-31). And check if the result of Date.parse isNaN let isValidDate = Date.parse(’01/29/1980′);

if (isNaN(isValidDate)) {
// when is not valid date logic

return false;
}

// when is valid date logic
Please take a look when is recommended to use Date.parse in MDN6
The function will return true if the given string is in the right format(‘MM/DD/YYYY’) else it will return false. (I found this code online & modified it a little) function isValidDate(date) {
var temp = date.split(‘/’);
var d = new Date(temp[2] + ‘/’ + temp[0] + ‘/’ + temp[1]);
return (d && (d.getMonth() + 1) == temp[0] && d.getDate() == Number(temp[1]) && d.getFullYear() == Number(temp[2]));
}

console.log(isValidDate(’02/28/2015′));5Find in the below code which enables to perform the date validation for any of the supplied format to validate start/from and end/to dates. There could be some better approaches but have come up with this. Note supplied date format and date string go hand in hand.
function validate() {

var format = ‘yyyy-MM-dd’;

if(isAfterCurrentDate(document.getElementById(‘start’).value, format)) {
alert(‘Date is after the current date.’);
} else {
alert(‘Date is not after the current date.’);
}
if(isBeforeCurrentDate(document.getElementById(‘start’).value, format)) {
alert(‘Date is before current date.’);
} else {
alert(‘Date is not before current date.’);
}
if(isCurrentDate(document.getElementById(‘start’).value, format)) {
alert(‘Date is current date.’);
} else {
alert(‘Date is not a current date.’);
}
if (isBefore(document.getElementById(‘start’).value, document.getElementById(‘end’).value, format)) {
alert(‘Start/Effective Date cannot be greater than End/Expiration Date’);
} else {
alert(‘Valid dates’);
}
if (isAfter(document.getElementById(‘start’).value, document.getElementById(‘end’).value, format)) {
alert(‘End/Expiration Date cannot be less than Start/Effective Date’);
} else {
alert(‘Valid dates’);
}
if (isEquals(document.getElementById(‘start’).value, document.getElementById(‘end’).value, format)) {
alert(‘Dates are equals’);
} else {
alert(‘Dates are not equals’);
}
if (isDate(document.getElementById(‘start’).value, format)) {
alert(‘Is valid date’);
} else {
alert(‘Is invalid date’);
}
}

/**
* This method gets the year index from the supplied format
*/
function getYearIndex(format) {

var tokens = splitDateFormat(format);

if (tokens[0] === ‘YYYY’
|| tokens[0] === ‘yyyy’) {
return 0;
} else if (tokens[1]=== ‘YYYY’
|| tokens[1] === ‘yyyy’) {
return 1;
} else if (tokens[2] === ‘YYYY’
|| tokens[2] === ‘yyyy’) {
return 2;
}
// Returning the default value as -1
return -1;
}

/**
* This method returns the year string located at the supplied index
*/
function getYear(date, index) {

var tokens = splitDateFormat(date);
return tokens[index];
}

/**
* This method gets the month index from the supplied format
*/
function getMonthIndex(format) {

var tokens = splitDateFormat(format);

if (tokens[0] === ‘MM’
|| tokens[0] === ‘mm’) {
return 0;
} else if (tokens[1] === ‘MM’
|| tokens[1] === ‘mm’) {
return 1;
} else if (tokens[2] === ‘MM’
|| tokens[2] === ‘mm’) {
return 2;
}
// Returning the default value as -1
return -1;
}

/**
* This method returns the month string located at the supplied index
*/
function getMonth(date, index) {

var tokens = splitDateFormat(date);
return tokens[index];
}

/**
* This method gets the date index from the supplied format
*/
function getDateIndex(format) {

var tokens = splitDateFormat(format);

if (tokens[0] === ‘DD’
|| tokens[0] === ‘dd’) {
return 0;
} else if (tokens[1] === ‘DD’
|| tokens[1] === ‘dd’) {
return 1;
} else if (tokens[2] === ‘DD’
|| tokens[2] === ‘dd’) {
return 2;
}
// Returning the default value as -1
return -1;
}

/**
* This method returns the date string located at the supplied index
*/
function getDate(date, index) {

var tokens = splitDateFormat(date);
return tokens[index];
}

/**
* This method returns true if date1 is before date2 else return false
*/
function isBefore(date1, date2, format) {
// Validating if date1 date is greater than the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) – 1,
getDate(date1, getDateIndex(format))).getTime()
> new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) – 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}

/**
* This method returns true if date1 is after date2 else return false
*/
function isAfter(date1, date2, format) {
// Validating if date2 date is less than the date1 date
if (new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) – 1,
getDate(date2, getDateIndex(format))).getTime()
< new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) – 1,
getDate(date1, getDateIndex(format))).getTime()
) {
return true;
}
return false;
}

/**
* This method returns true if date1 is equals to date2 else return false
*/
function isEquals(date1, date2, format) {
// Validating if date1 date is equals to the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) – 1,
getDate(date1, getDateIndex(format))).getTime()
=== new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) – 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}

/**
* This method validates and returns true if the supplied date is
* equals to the current date.
*/
function isCurrentDate(date, format) {
// Validating if the supplied date is the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) – 1,
getDate(date, getDateIndex(format))).getTime()
=== new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}

/**
* This method validates and returns true if the supplied date value
* is before the current date.
*/
function isBeforeCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) – 1,
getDate(date, getDateIndex(format))).getTime()
new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}

/**
* This method splits the supplied date OR format based
* on non alpha numeric characters in the supplied string.
*/
function splitDateFormat(dateFormat) {
// Spliting the supplied string based on non characters
return dateFormat.split(/\W/);
}

/*
* This method validates if the supplied value is a valid date.
*/
function isDate(date, format) {
// Validating if the supplied date string is valid and not a NaN (Not a Number)
if (!isNaN(new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) – 1,
getDate(date, getDateIndex(format))))) {
return true;
}
return false;
}

Below is the HTML snippet

2Here is one snippet to check for valid date: function validateDate(dateStr) {
const regExp = /^(\d\d?)\/(\d\d?)\/(\d{4})$/;
let matches = dateStr.match(regExp);
let isValid = matches;
let maxDate = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

if (matches) {
const month = parseInt(matches[1]);
const date = parseInt(matches[2]);
const year = parseInt(matches[3]);

isValid = month 0;
isValid &= date 0;

const leapYear = (year % 400 == 0)
|| (year % 4 == 0 && year % 100 != 0);
isValid &= month != 2 || leapYear || date <= 28;
}

return isValid
}

console.log(['1/1/2017', '01/1/2017', '1/01/2017', '01/01/2017', '13/12/2017', '13/13/2017', '12/35/2017'].map(validateDate));2It’s ok if you want to check validate dd/MM/yyyy function isValidDate(date) {
var temp = date.split(‘/’);
var d = new Date(temp[1] + ‘/’ + temp[0] + ‘/’ + temp[2]);
return (d && (d.getMonth() + 1) == temp[1] && d.getDate() == Number(temp[0]) && d.getFullYear() == Number(temp[2]));
}

alert(isValidDate(’29/02/2015′)); // it not exist —> false2

Javascript: Data Validation Form – Stack Overflow
javascript – How to implement data validation in Excel

See more results