Custom rule Form_Validation for school year (Ex: 2001/2002) - php

I am a newbie
I got a problem, I want to custom rule in form validation for school year
There is an input box, user have to type like this: 2001/2002 or 2013/2014 or 2017/2018 without any exception
In my controller code:
$this->form_validation->set_rules('nama_tahun_ajaran','nama_tahun_ajaran','required|max_length[9]|callback_valid_name');
function $valid_name($nama_tahun_ajaran){
// RIGHT HERE I'M STILL Have no Idea to makes a rule
}
I hope you understand what I ask
Thanks

You could use a regular expression to match the string, then make a simple comparison to ensure the years are within a year of each other and are in the valid order.
function valid_name($nama_tahun_ajaran = null)
{
// Regex patterns for year and forward slash
$year = '((?:(?:[1]{1}\\d{1}\\d{1}\\d{1})|(?:[2]{1}\\d{3})))(?![\\d])';
$slash = '(\\/)';
// Does the inputted value matche the regex?
// Checks it's in the form 'year/year'. E.g. '2010/2012'.
if (preg_match_all("/".$year.$slash.$year."/is", $nama_tahun_ajaran, $matches))
{
// Get the years from the string
$first_year = $matches[1][0];
$second_year = $matches[3][0];
// Is the first year one less than the second year?
if (($first_year + 1) == $second_year)
{
return TRUE;
}
}
return FALSE;
}
This will only work with years in the range 1000-2999.

Related

PHP DD/MM/YYYY Validation [duplicate]

This question already has answers here:
My pattern isn't matching a ISO style date, why? [duplicate]
(3 answers)
Closed 7 years ago.
apologies for probably a simple question, but i am new to PHP and Javascript.
I am creating a login validation in PHP that requires a registering user to input their date of birth in a DD/MM/YYYY Format, that returns an error message if the date is entered in any other format. I am unsure how to do this, other than using preg_match, however this doesnt seem to work...
variables:
$DOB = $_POST['DOB'];
$error_message = '';
The Date Validation Segment
elseif (!preg_match("/^(0?[1-9]|[12][0-9]|3[01])\/\.- \/\.- \d{2}$/", $DOB))
{
$error_message = 'Invalid Date';
}
Error Display
if ($error_message != '')
{
echo 'Error: '.$error_message.' Go Back.';
echo '</body> </html>';
exit;
}
else
{
echo'<p><strong>Form Submitted Successfully!</strong></p>';
}
This is not a duplicate, i tried other threads and none of their solutions worked.
You should use more than a regular expression. For example, you should not allow something like 31/02/2015, because there's no 31th in February!
I have a function that works well:
function isDate($string) {
$matches = array();
$pattern = '/^([0-9]{1,2})\\/([0-9]{1,2})\\/([0-9]{4})$/';
if (!preg_match($pattern, $string, $matches)) return false;
if (!checkdate($matches[2], $matches[1], $matches[3])) return false;
return true;
}
It first uses preg_match to check for the formal validity of DD/MM/YYYY, grabbing DD, MM and YYYY portions into the $matches array. Then it check the validity of the date itself using the built-in PHP function checkdate.
You can use that in your code like:
if (!isDate($DOB)) {
$error_message = 'Invalid Date';
}
string_explode given string and then pass parts of it to
bool checkdate ( int $month , int $day , int $year )
unfortunately you cannot know if user posted month and day in your format if day is not greater than 12
You can do it like this in PHP:
$date=explode("/",$_POST['DOB']);
if(checkdate ($date[1] ,$date[0] ,$date[2]))
{
echo "valid";
}
else
{
echo "invalid";
}
checkdate will only return true if the three value behind "/" is valid, so if there's no "/" its invalid, same as they put numbers in wrong order.
check manual http://php.net/manual/en/function.checkdate.php

PHP if statements for numbers/digits greater than/less than

I have a little puzzle I'm trying to solve with no joy yet. I want to have a set of ifelse statements filter a number variable. Sort of like this.
If the assets are greater than 1500000, make the value down to a 6 digit number maximum using the numbers existing.
If the assets is smaller than 599999, make the value up to a 6 digit maximum using the numbers existing.
If the assets is between 599999 and 1500000, leave the variable alone and let it pass.
if ($assets > 1500000) {
$assets_calc = preg_match_all('/(\d{6})/', $assets_array, $matches);
}
elseif ($assets < 599999) {
$assets_calc = preg_match_all('/someregex here/', $assets_array, $matches);
} else {
$assets = $assets
}
Not sure if that is possible.
Not sure if this answers your question but are you looking to simply truncate digits of each value in the array?
if ($assets > 1500000)
{
foreach($assets_array as $k=>$v)
{
$assets_calc[$k] = (int)substr((string)$v, 0, 6);
}
}
// implement substring() in rest of code here

Check whether day is specified in a date string

Test case scenario - User clicks on one of two links: 2012/10, or 2012/10/15.
I need to know whether the DAY is specified within the link. I am already stripping the rest of the link (except above) out of my URL, am I am passing the value to an AJAX request to change days on an archive page.
I can do this in either JS or PHP - is checking against the regex /\d{4}\/\d{2}\/\d{2}/ the only approach to seeing if the day was specified or not?
You can also do this if you always get this format: 2012/10 or 2012/10/15
if( str.split("/").length == 3 ) { }
But than there is no guaranty it will be numbers. If you want to be sure they are numbers you do need that kind of regex to match the String.
You could explode the date by the "/" delimiter, then count the items:
$str = "2012/10";
$str2 = "2012/10/5";
echo count(explode("/", $str)); // 2
echo count(explode("/", $str2)); // 3
Or, turn it into a function:
<?php
function getDateParts($date) {
$date = explode("/", $date);
$y = !empty($date[0]) ? $date[0] : date("Y");
$m = !empty($date[1]) ? $date[1] : date("m");
$d = !empty($date[2]) ? $date[2] : date("d");
return array($y, $m, $d);
}
?>
I would personally use a regex, it is a great way of testing this sort of thing. Alternatively, you can split/implode the string on /, you will have an array of 3 strings (hopefully) which you can then test. I'd probably use that technique if I was going to do work with it later.
The easiest and fastest way is to check the length of the string!
In fact, you need to distinguish between: yyyy/mm/dd (which is 10 characters long) and yyyy/mm (which is 7 characters).
if(strlen($str) > 7) {
// Contains day
}
else {
// Does not contain day
}
This will work EVEN if you do not use leading zeros!
In fact:
2013/7/6 -> 8 characters (> 7 -> success)
2013/7 -> 6 characters (< 7 -> success)
This is certainly the fastest code too, as it does not require PHP to iterate over the whole string (as using explode() does).

Numeric input validation in PHP

I'm trying to validate an input for Account number in php form. It should contain 8 numbers and '-' optionally. If there is '-' - it should be ignored.
After pressing the Submit button, the warning message suppose to be displayed above the form in case input is invalid.
Please help.
This is what I got so far, but I'm not sure if this is correct and don't know how to display a warning message above the form.
$acctnum= "$acctnum";
if(empty($acctnum)){
echo "You did not enter an account number, please re-enter"; }
else if(!preg_match("\-^[0-9]{8}", $acctnum)){
echo "Your account number can only contain eight numbers. Please re-enter."; }
Thank you!
You don't appear to be trying. No documentation or tutorial will tell you to make a Regex like that. For starters, where are the delimiters? Why is - escaped when it's outside a character class and therefore has no special meaning? What is that ^ doing there?
This should do it:
$acctnum = str_replace("-","",$acctnum);
if( !preg_match("/^\d{8}$/",$acctnum)) echo "Error...";
Since regex are quite expensive I'd go like that instead:
$acctnum = (int) $acctnum; // this automatically ignore the '-'
if ($acctnum < 0) $acctnum = -$acctnum;
$digits = ($acctnum == 0) ? log10($acctnum) + 1 : 1;
if ($digits === 8) { ... }
Split the task in two. First get rid of the "-" with str_replace and then check for the numbers.
$match = preg_match("/^\d{8}$/", str_replace("_", "", $str));
if ($match > 0) {
// Correct
} else {
// incorrect
}

looking to validate US phone number w/ area code

I'm working on a function to validate a US phone number submitted by a user, which can be submitted in any of the popular number formats people usually use. My code so far is as follows:
$number = '123-456-7890';
function validate_telephone_number($number) {
$formats = array(
'###-###-####',
'(###)###-###',
'(###) ###-###',
'##########'
);
$number = trim(preg_replace('[0-9]', '#', $number));
if (in_array($number, $formats)) {
return true;
} else {
return false;
}
}
First off, this code does not seem to be working, and returns false on all submitted numbers. I can't seem to find my error.
Secondly, I'm looking for an easy way to only allow phone numbers from an array of specific allowed area codes. Any ideas?
For your first question:
preg_replace('/[0-9]/', '#', $number)
or '/\d/'
For the second question this may help you:
$areaCode = substr(preg_replace('/[^\d]/', '', $number),0 , 3);
This will give you the first 3 digits in the number by discarding all other characters.
I'm not familiar with the US area codes format so I cannot help you more with this one.
Bonus:
if (in_array($number, $formats)) {
return true;
} else {
return false;
}
is equivalent to
return in_array($number, $formats);
As a matter of fact any statement of the form
if(<expression>){
return true;
}
else{
return false;
}
can be written as return (bool) <expr>;, but in this case in_array will always return a Boolean so (bool) is not needed.
Your code does not check for well formatted but invalid numbers - for example, no area code starts with 0 or 1 in the US, so this could be checked. Also, your formats do not allow for country code inclusion - +15551234567 would be rejected, for example.
If you don't care about the formatting and just want to validate if the digits in the input amount to a valid US phone number, you could use something like this:
$clean_number = preg_replace("/[^0-9]/", '', $number);
$valid = preg_match("/^(\+?1)?[2-9][0-9]{9}$/", $clean_number);
Of course, this will also accept "foo 5555555555 bar" as a valid number - if you want to disallow that, make the preg_replace more restrictive (e.g, remove only brackets, spaces and dashes).
If you prefer to do this without maintaining a lot of code, you an check out this API that validates a US number and provides several formats for the number https://www.mashape.com/parsify/format
Look here for a code project that has a function for validating phone numbers.

Categories