Question

I have a HTML form in list.php that submits the data from text box ("item" in below code) to check.php. This check.php validates the text entered to be not empty or white spaces only. After validation, it redirects to list.php for the entered text to be displayed. list.php is below. I want the "add" button to be enabled only when valid text is entered in the text box. I would like this feature to be done with php and probably not with javascript.

I can use "disabled=\"disabled\" in the form, but this does not work in real-time disabling depending on validation.

<form action="check.php" method="post">

<input name="item" type="text" size="25" autofocus="autofocus" />

<input type="submit" value="Add" id="add" />

</form>
Was it helpful?

Solution

You say:

I would like this feature to be done with php and probably not with javascript.

Unfortunately, if you want "real-time" then you're gonna need JavaScript. You'll need it to make AJAX calls to your PHP code to check for validation.

So either A) you don't validate in "real-time" at all, or B) You use JavaScript in one shape or another.

Let's say you opt for B), to use JavaScript, and presuming ALL you need to do is check for an empty string or whitespace, then you can do all of this client-side in JavaScript and not require a server call at all, also making it truly "real-time".

And so, here is my solution, using JavaScript (jQuery) without relying on server calls. This may not be suitable for your current implementation, but just in case it is, this might be helpful.

JSFiddle:
http://jsfiddle.net/VKfrw/1/

JavaScript:

function hasWhiteSpaceOrEmpty(s) 
{
  return s == "" || s.indexOf(' ') >= 0;
}

function validateInput()
{
    var inputVal = $("#myInput").val();
    if(hasWhiteSpaceOrEmpty(inputVal))
    {
        //This has whitespace or is empty, disable the button
        $("#add").attr("disabled", "disabled");
    }
    else
    {
        //not empty or whitespace
        $("#add").removeAttr("disabled");
    }
}

$(document).ready(function() {
    $("#myInput").keyup(validateInput);
});

HTML:

<!-- give this guy an ID -->
<input id="myInput" name="item" type="text" size="25" autofocus="autofocus" />

This implementation uses jQuery.

OTHER TIPS

As mentioned, if you want this done in real time some javascript will be needed.

However I think this problem is actually more suited to javascript in general. PHP validation can be useful if you need to cross reference for data with data in your database. eg. In a sign up form, checking a user is not already registered with the entered email address.

But in your case, depending on what you mean by "valid text" it is probably easier and better to use javascript.

There are some great jQuery plugins which make javascript validation really simple. http://docs.jquery.com/Plugins/Validation/validate

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top