October 13, 2012

Check whether an input string contains number

Question by Udara S.S Liyanage

I want to check whether an input string contains number.

I am trying to validate an input field. I want it to contain only alphabet, not numbers.

Answer by Starx

You can do this using javascript. No need for Jquery or Regex

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

While implementing

var val = $('yourinputelement').val();
if(isNumeric(val)) { alert('number'); } 
else { alert('not number'); }

Update: To check if a string has numbers in them, you can use regular expressions to do that

var matches = val.match(/d+/g);
if (matches != null) {
    alert('number');
}
July 4, 2010

How to do Php Security check for input fields and input treatment?

Question by Yosef

How to do Php Security check for input user fields and input user treatment(please if you can solve example1+2)?

Example1: check if user insert url or something else:

<label>url: </label>
<input type="text">

Example2: check if user insert html or something else

<label>paste html: </label>
<textarea></textarea>

thanks

Answer by h3xStream

1. For the validation of URLs :

$validUrl = strpos($url, "http://") === 0;
if(!$validUrl) $url = "http://".$url;

When the link is return to the user, use htmlentities().

2. For the validation of HTML code, use a lib like http://htmlpurifier.org/.

<?php
require_once 'htmlpurifier/HTMLPurifier.auto.php';

$purifier = new HTMLPurifier();
$clean_html = $purifier->purify($_GET['dirty_html']);
echo $clean_html;
?>

With the input :

<img src="test.gif" onload="alert('xss')"/>

The result is :

<img src="test.gif" alt="test.gif" />
...

Please fill the form - I will response as fast as I can!