I'm really new in internet languages and i try to figure out how it's possible to validate the users input before method call but i just can't make it work yet.
<html>
<head>
</head>
<body>
<?php
$grade = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$returned = test_input($_POST["grade"]);
if(!$returned) ?
}
function test_input($data)
{
if ( !is_numeric($data) || $data>100 || $data<0 )
{
$data = "";
echo 'The input should be a number between 0 and 100 ';
echo "<br>";
echo 'Try again';
return false;
}
return true;
}
?>
<form action = "file_1_2.php" method = "post">
Grade: <input type="text" name="grade">
</form>
</body>
</html>
Further to my and other comments, your function has incorrect if clauses, specifically your greater than, less than. I would suggest not echoing any strings from it otherwise you have a limited-use function.
function input_valid($data = false)
{
if(empty($data))
return false;
elseif($data && !is_numeric($data))
return false;
else
return (($data <= 100) && ($data > 0));
}
if(isset($_POST["grade"])) {
if(input_valid($_POST["grade"])) {
// Do stuff.
}
else {
echo 'Invalid input. Must be a number between 1 and 100.';
}
}
NOTE: I feel it's important to re-iterate my comment above which is you SHOULD NOT rely solely on client-side validation. The user can turn it off, then you have no validation. Client-side validation should be considered only as a "user experience" feature, not a "security" feature.
You can try using jquery
<form action = "file_1_2.php" method = "post">
Grade: <input type="text" name="grade" class="grade" onkeyup="">
</form>
<script type='text/javascript' src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script>
$(function(){
$('input.grade').bind("keyup change", function(){
validateGrade( $(this).val() );
});
});
function validateGrade(g){
if(g>100 || g<0){
alert('The input should be a number between 0 and 100');
}
}
</script>
Related
I want the user to fill at least 1 out of 3 fields in the search form is it possible?
here is the link
http://img.needforgaming.x10.mx/procurar.php
i dont want user to have empty fields and search to apper all the data...
In your procurar.php file you should apply the check condition.
Use the below code:
if(isset($_REQUEST['btn_procurar'])){
if(empty($_REQUEST["Cliente_procurar"]) && empty($_REQUEST["N24H_procurar"]) && empty($_REQUEST["NS24_procurar"])) {
echo "Please fill At least a field";
} else {
//your code to search and other
}
}
Above code is server side if you want to check it client side then use the javascript.
Use client side or server side validation for it. You just need to check if anyone of the three textboxes has a value or not. OR all the text boxes having empty values. In javascript, you can check it as follows:
if((document.getElementById('text1').value == '') && (document.getElementById('text2').value == '') && (document.getElementById('text3').value == ''))
{
alert('Enter any values for search');
return false;
}
You can do it using PHP
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['search1'])||!empty($_POST['search2'])||!empty($_POST['search3'])){
echo "Do Search";
}
else{
echo "you mush fill at least one field";
}
}
?>
<form action="" method="post">
<input type="text" name="search1">
<input type="text" name="search2">
<input type="text" name="search3">
<input type="submit" value="Search" name="submit">
</form>
You should write javascript code to check:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function () {
$(document.forms[0]).submit(function () {
canSubmit = false;
$('form input:text').each (function () {
if($(this).val().length > 0)
canSubmit = true;
});
return canSubmit;
});
});
<script>
function verification()
{
var1= document.getElementById("formProcurar").value;
var2= document.getElementById("formProcurar").value;
var3= document.getElementById("formProcurar").value;
if((var1 != "") && (var2 != "") && (var3 != ""))
{
// do what ever you want here.
}
else
{
alert("Fill at least one field");
}
}
Use java script for the task this will be user friendly as the page does not need to refresh
I'm trying to validate some form fields using JS functions, but they don't seem to load or check the field when the submit button is clicked.
<html>
<body>
<?php require_once('logic.php'); ?>
<h1>Add new Region/Entity</h1>
<?php
if ($_POST['submitted']==1) {
echo $error;
}
?>
<form action="logic.php" method="post" name="registration" onSubmit="return formValidation();">
Region: <input type="text" name="region" value="<?php echo #$_POST['region']; ?>"><br>
Description: <br><textarea name="description" cols="50" rows="10"><?php echo #$_POST['description']; ?></textarea><br>
Remarks: <input type="text" name="remarks" value="<?php echo #$_POST['remarks']; ?>">
<input type="hidden" name="submitted" value="1"><br>
<input type="submit" value="Submit" onclick="">
And here's the JS:
<script type="text/javascript">
function formValidation() {
var region = document.registration.region;
var descr = document.registration.description;
var remarks = document.registration.remarks;
if(empty_validation()) {
if(reg_validation()) {
if(reg_letters()) {
if (desc_letters()) {
if (desc_validation()) {
}
}
}
}
}
return false;
}
function empty_validation() {
var reg_len = region.value.length;
var descr_len = descr.value.length;
var rem_len = remarks.value.length;
if (reg_len == 0 || decr_len == 0 || rem_len == 0) {
alert("Please fill all the fields");
return false;
}
return true;
}
function reg_validation() {
if (reg_len > 50) {
alert("Only 50 characters are allowed in the Region field");
region.focus();
return false;
}
return true;
}
function reg_letters() {
var letters = /^[A-Za-z]+$/;
if(region.value.match(letters)) {
return true;
} else {
alert('Region field must have only alphabetical characters');
region.focus();
return false;
}
}
function desc_validation() {
if (descr_len > 500) {
alert("Only 500 characters are allowed in the description field");
descr.focus();
return false;
}
return true;
}
function desc_letters() {
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < descr_len; i++) {
if (iChars.indexOf(descr.value.charAt(i)) != -1) {
alert ("Your description has special characters. \nThese are not allowed.\n Please remove them and try again.");
return false;
}
}
return true;
}
</script>
</form>
</body>
</html>
As you can see, I'm posting values from the form to a PHP file. And I've used the onSubmit event in the form tag to initialize the formValidation() function. It isn't working for some reason.
Here's a working example if you need one.
I'm not going to fix every little error you have, but the main problem is that variables aren't defined where you expect them to be. You can't declare a variable in one function and expect it to be available in the next (without passing it as a parameter or declaring it globally). For example, your empty_validation function should be this:
function empty_validation(region, descr, remarks) {
var reg_len = region.value.length;
var descr_len = descr.value.length;
var rem_len = remarks.value.length;
if (reg_len == 0 || decr_len == 0 || rem_len == 0) {
alert("Please fill all the fields");
return false;
}
return true;
}
And in your formValidation function, you call it like this:
if(empty_validation(region, descr, remarks)) {
This is just one example, and you would need to do it in a few places.
A few other things - you always return false from formValidation...did you mean to put return true; inside the innermost if statement? Also, since all you seem to be doing is calling each of those functions, you can probably put them into one big if statement, like this:
if (empty_validation() && reg_validation() && reg_letters() && desc_letters() && desc_validation()) {
return true;
}
return false;
i've created exception using JS so that user are only allowed to input numbers to the html form field. this is working nicely but the problem is, the Submit button isn't working anymore. if i remove the exception code, submit button is working nicely! i can't understand where is the problem. anyone can help please? thanks in advance!
here is the exception:
function validateNum(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate()
{
if( document.myForm.ic.value == "" ||
isNaN( document.myForm.ic.value ) ||
document.myForm.ic.value.length != 12)
{
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;
}else{
// Put extra check for data format
var ret = validateNum();
if( ret == false )
{
return false;
}
}
here is my html form action:
<form name="myForm" method="post" action="nonuum_reg.php" onsubmit="return(validate());">
and here is the input field & submit button:
<input name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
<input type="submit" value="Apply" />
Try this one as my explanation on my comment on your question:
<form name="myForm" method="post" action="nonuum_reg.php" onsubmit="validate(event);">
<input name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
<input type="submit" value="Apply" />
</form>
<script>
function validateNum(evt) {
var theEvent = evt;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate(evt){
if( document.myForm.ic.value == "" || isNaN( document.myForm.ic.value ) || document.myForm.ic.value.length != 12) {
evt.preventDefault();
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;
}
}
</script>
You should still create validation on your PHP controller to prevent if users turn off javascript on theirs browser.
Try adding a return true in you =r else close
...
else{
// Put extra check for data format
var ret = validateNum();
if( ret == false )
{
return false;
}
return true;
}
...
This should also help you (not the same issue but same code)link:
I have been digging around on here and other sites for a while and am stuck. I'm trying to use jQuery to validate my form (concurrently as the user fills out the form) and, if the form is valid have it submit to a php page I have created to process the contents of the form. I have been able to have it validate but I can't have it also submit it...if I put a value in for the form action parm then it bypasses the validation. Please help...
I apologize, in advance, for the bad coding.
Here is my jquery-validate.js:
//global vars
var form = $("#customForm");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var pass1Info = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var message = $("#message");
function validateName(){
//if it's NOT valid
if(name.val().length < 4){
name.addClass("error");
nameInfo.text("We want names with more than 3 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else{
name.removeClass("error");
nameInfo.text("What's your name?");
nameInfo.removeClass("error");
return true;
}
}
function validatePass1(){
var a = $("#password1");
var b = $("#password2");
//it's NOT valid
if(pass1.val().length <5){
pass1.addClass("error");
pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
pass1Info.addClass("error");
return false;
}
//it's valid
else{
pass1.removeClass("error");
pass1Info.text("At least 5 characters: letters, numbers and '_'");
pass1Info.removeClass("error");
validatePass2();
return true;
}
}
function validatePass2(){
var a = $("#password1");
var b = $("#password2");
//are NOT valid
if( pass1.val() != pass2.val() ){
pass2.addClass("error");
pass2Info.text("Passwords doesn't match!");
pass2Info.addClass("error");
return false;
}
//are valid
else{
pass2.removeClass("error");
pass2Info.text("Confirm password");
pass2Info.removeClass("error");
return true;
}
}
function validateMessage(){
//it's NOT valid
if(message.val().length < 10){
message.addClass("error");
return false;
}
//it's valid
else{
message.removeClass("error");
return true;
}
}
/*
Validate the name field in: blur and keyup events.
Validate the email field in: blur event.
Validate the password fields in: blur and keyup events.
Validate the message field in: blur, and keyup event.
Validate all fields in: submit form event
*/
//On blur
name.blur(validateName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
//On key press
name.keyup(validateName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
message.keyup(validateMessage);
//On Submitting
form.submit(function(){
if(validateName() && validateEmail() && validatePass1() && validatePass2() && validateMessage())
return true;
else
return false;
});
My form code is pasted here:
<form method="post" id="customForm" action="rcv-form1.php">
<div>
<label for="name">Name</label>
<input id="name" name="name" type="text" />
<span id="nameInfo">What's your name?</span>
</div>
<div>
<label for="email">E-mail</label>
<input id="email" name="email" type="text" />
<span id="emailInfo">Valid E-mail please, you will need it to log in!</span>
</div>
<div>
<label for="pass1">Password</label>
<input id="pass1" name="pass1" type="password" />
<span id="pass1Info">At least 5 characters: letters, numbers and '_'</span>
</div>
<div>
<label for="pass2">Confirm Password</label>
<input id="pass2" name="pass2" type="password" />
<span id="pass2Info">Confirm password</span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message" cols="" rows=""></textarea>
</div>
<div>
<input id="send" name="send" type="submit" value="Send" />
</div>
</form>
And here is my php that receives the form (this is just for testing now. i will email or insert into mySQL once i know i can properly validate stuff):
<html><head>
<title>Display form values</title>
</head>
<body>
<?
//$valid_form = TRUE;
//$bad_field_count = 0;
$table1_beg = '<center><table align="center" bordercolor="#F00" width="600px" border="3" cellspacing="1" cellpadding="1"><caption>Form status</caption><tr><th scope="col">Field Name</th><th scope="col">Field Value</th></tr>';
$row_beg = '<tr><td>';
$td = '</td><td>';
$row_end = '</td></tr>';
$table1_end = '</table></center>';
function checkEmail($field)
{
if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
//echo "This ($field) email address is considered valid.";
return $field;
} else {
$field = filter_var($field, FILTER_SANITIZE_EMAIL);
//global $bad_field_count; $bad_field_count++;
return $field;
}
}
function SanitizeString($field)
{
$field = filter_var($field, FILTER_SANITIZE_STRING);
//if(is_null($field) || $field == '') { global $bad_field_count; $bad_field_count++;}
return $field;
}
// ensure form data is valid
$name=SanitizeString($_POST['name']);
//$email=$_POST['email'];
$email = checkEmail($_POST['email']);
$pass1=SanitizeString($_POST['pass1']);
$pass2=SanitizeString($_POST['pass2']);
$message=SanitizeString($_POST['message']);
echo $table1_beg;
echo $row_beg . "Name" . $td . "<u>" . $name . "</u>" . $row_end;
echo $row_beg . "Email" . $td . "<u>" . $email . "</u>" . $row_end;
echo $row_beg . "Password 1" . $td . "<u>" . $pass1 . "</u>" . $row_end;
echo $row_beg . "Password 2" . $td . "<u>" . $pass2 . "</u>" . $row_end;
echo $row_beg . "Message" . $td . "<u>" . nl2br($message) . "</u>" . $row_end;
//echo $row_beg . "Number of bad fields" . $td . "<b>" . $bad_field_count . "</b>" . $row_end;
echo $table1_end;
//}
?>
</body></html>
Problem 1: When I have form action="" I can validate the form only after hitting submit...it doesn't say it's invalid until after submitting when I thought it should do it concurrently as it is typed in.
Problem 2: If I have my form action set to anything but "" it will ignore the jQuery validation all together.
I'm new to the form validation stuff. Can someone point me in the right direction? Thanks, in advance!
You have a few problems, your form submit code doesn't have curly brackets around it, and you don't have a function for validate email, try this:
//global vars
var form = $("#customForm");
var fname = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var pass1Info = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var message = $("#message");
function validateName() {
//if it's NOT valid
if (fname.val().length < 4) {
fname.addClass("error");
nameInfo.text("We want names with more than 3 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else {
fname.removeClass("error");
nameInfo.text("What's your name?");
nameInfo.removeClass("error");
return true;
}
}
function validatePass2() {
var a = $("#password1");
var b = $("#password2");
//are NOT valid
if (pass1.val() != pass2.val()) {
pass2.addClass("error");
pass2Info.text("Passwords doesn't match!");
pass2Info.addClass("error");
return false;
}
//are valid
else {
pass2.removeClass("error");
pass2Info.text("Confirm password");
pass2Info.removeClass("error");
return true;
}
}
function validatePass1() {
var a = $("#password1");
var b = $("#password2");
//it's NOT valid
if (pass1.val().length < 5) {
pass1.addClass("error");
pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
pass1Info.addClass("error");
return false;
}
//it's valid
else {
pass1.removeClass("error");
pass1Info.text("At least 5 characters: letters, numbers and '_'");
pass1Info.removeClass("error");
validatePass2();
return true;
}
}
function validateMessage() {
//it's NOT valid
if (message.val().length < 10) {
message.addClass("error");
return false;
}
//it's valid
else {
message.removeClass("error");
return true;
}
}
function validateEmail(){
//add validation for email here
return true;
}
/*
Validate the name field in: blur and keyup events.
Validate the email field in: blur event.
Validate the password fields in: blur and keyup events.
Validate the message field in: blur, and keyup event.
Validate all fields in: submit form event
*/
//On blur
fname.blur(validateName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
//On key press
fname.keyup(validateName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
message.keyup(validateMessage);
//On Submitting
form.submit(function() {
if (validateName() && validateEmail() && validatePass1() && validatePass2() && validateMessage()) {
return true;
}
else {
return false;
}
});
I've gave you an easy way to validate your all inputs/textarea within one function but you have to complete it, I've just gave you the structure and only name validation has done as an example for you and I hope you can understand it easily. If you need more help/difficulties just leave a message. This should be placed inside ready event.
var info={
'nameInfo':$("#nameInfo"),
'emailInfo':$("#emailInfo"),
'pass1Info':$("#pass1Info"),
'pass2Info':$("#pass2Info")
}
$('#customForm input,textarea').not("#send").bind('blur keyup', function(e)
{
e.stopPropagation();
var el=$(e.target);
var id=el.attr('id');
if(el.attr('id')=='message' && e.type=="keyup")
{
return false;
}
else
{
if(id=="name")
{ if(el.val().length < 4)
{
el.addClass("error");
info.nameInfo.text("We want names with more than 3 letters!");
info.nameInfo.addClass("error");
return false;
}
else
{
el.removeClass("error");
info.nameInfo.text("What's your name ?");
info.nameInfo.removeClass("error");
return true;
}
}
if(id=="email")
{
// Your email validation code
}
if(id=="pass1")
{
// Your pass1 validation code
}
if(id=="pass2")
{
// Your pass2 validation code
}
if(id=="message")
{
// Your message validation code
}
}
});
This code is supposed to check to see if any fields are blank or invalid, if they are, it will turn them red. if all is ok then it will send to the database.
The problem is, if the last 'if' is not met, then the 'else' will fire.
This means as long as a valid email address is entered the form will submit, even if other fields are blank.
How can I make so that all requirements must be met for the form to submit
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
else {
//submits to database...
}
You can use a flag as:
$isValid = true;
if(empty($_POST['company'])) {
$isValid = false;
// your echo
}
Similarly add the $isValid = false; for all the other if bodies.
Finally remove your else part and replace it with:
if($isValid) {
// submit to DB.
}
you either can use else if, but then you won't see your "red" for all wrong fields but only for the first that failed validation.
like so:
if() {
} elseif() {
} else {
...
}
or you could set something to $error=false at the beginning, and set error to true inside the if controlled code and the submission to database checks if error is still false...
<?php
$error = 1;
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if($error == 1) { //submits to database...
}
?>
There is a far better way of doing this instead of repeating your own code for each POST variable, which is not efficient.
// loop through all submitted fields
foreach( $_POST as $key => $value){
// see if the field is blank
if($value=="" || $value is null){
// if blank output highlighting JS
echo "<script type='text/javascript'>
$(document).ready(function() {
$('#".$key."Form').animate({backgroundColor:'#ffbfbf'},500);
});
</script>";
// variable to value showing form is invalid in some way
$invalid=1;
}
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$invalid= 1;
}
// if form invalid variable not set, submit to DB
if($invalid!=1){
// submit to DB
}
If you want to be super efficient you can simply use:
// search for any values that are null (empty fields)
$invalid_fields=array_keys($_POST, null);
// you may need to use $invalid_fields=array_keys($_POST, "");
// if there are any results from this search, loop through each to highlight the field
if($invalid_fields){
foreach( $invalid_fields as $key => $value){
echo "<script type='text/javascript'>
$(document).ready(function() {
$('#".$value."Form').animate({backgroundColor:'#ffbfbf'},500);
});
</script>";
}
$error = 1;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 1;
}
if($error!=1){
// submit to DB
}
Introduce a Variable $sendToDb and initialy set it to (bool) true. If any of your checks fails, set this variable to false.
Then rewrite the else-Part and do a
if ($sendToDb) {
/* Your Db-Write code */
}
Take a flag variable and check like this
$flag=0;
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if ($flag == 0)
{//submit to database
}
You really shouldn't be mixing server-side code (PHP) with client-side code (JavaScript).
Validate on the server side first. Then add validation on the client side. The reason being, if your user has JavaScript enabled then they'll get the error messages before the form submits. If they have JavaScript disabled, then your PHP script will throw the errors. Something like the following script:
<?php
if (isset($_POST['submit'])) {
$errors = array();
// do server-side validation
if ($_POST['fieldName'] == '') {
$errors['fieldName'] = 'fieldName is required';
}
if (count($errors) == 0) {
// save your record to the database or whatever
}
}
And then the following template:
<style>
.error { border-color: red; }
</style>
<script>
$(document).ready(function() {
$('form#yourFormId').submit(function() {
var errors = null;
if (errors.length > 0) {
return false;
}
});
});
</script>
<form action="yourScript.php" method="post" id="yourFormId">
<input type="text" name="fieldName" value="" id="id"<?php if (in_array('fieldName', $errors)) echo ' class="error"'; ?>>
<input type="submit" name="submit">
</form>
This will apply a class of .error to any invalid form fields, first by JavaScript and then server-side.