Julie Julie - 3 days ago 5
PHP Question

How to get clear copy paste data into a form

I'm not sure if this title is the correct title for this question.
My problem is.. a have a form, which need to be fill in by copy & paste from a document.

The following is my code:

// length of rrnNo = 12 character, could be append with spaces and start with spaces as well
$RRN = $this->input->post('rrnNo');

// do some search using $RRN
$checkRRN = strpos($text, $RRN)

if ($checkRRN !== FALSE)
{
print $text;
}


I hit a bug whereby, when the user copy and paste whole 12 digit, no search results display. But when they copy and paste the last 9 digit, they manage to get the results. So what I did was..

// length of rrnNo = 12 character, could be append with spaces and start with spaces as well
$RRN = $this->input->post('rrnNo');

// get last 9 digits
$shortRRN = substr($rrn,-9);

// do some search using shortRRN
$checkRRN = strpos($text, $shortRRN)

if ($checkRRN !== FALSE)
{
print $text;
}


But still doesn't work with 12 digits. They still need to paste data with 9 digits to get the results. Appreciate your advice/opinion.
Thanks

Answer

Use this code

$RRN = trim($this->input->post('rrnNo',true));
//trim the string to remove spaces before and after, and the second parameter is for xss handling (security) 

if (strpos(trim($text), $RRN) )
{
   print $text;
}

Also, if you want to make sure that the user provides exactly 12 characters, load the form-validation library and do a quick validation like this.

$this->form_validation->set_rules('rrnNo',"RNN number",'trim|required|min_length[12]|max_length[12]');
if ($this->form_validation->run()){
  //write your code in here
}
Comments