Since there is no minlength="" for input, how can I make an if statement that does the following:
If the user has not input more than 3 characters it will not be saved in a database.
Here is the input:
QTY<input title="QUANTITY PER ITEM" size="1" name="inputQTY" value="**(minimun of 3 characters)**"/>
any ideas??
Note: it doesn't matter if there's a min value restriction on the input field or not; a user can still spoof the form to contain whatever value he or she wants. Thus, you need to validate on the server side.
Let's say you're using PHP as your server side language.
$inputQTY = $_POST['inputQTY'];
if (strlen($inputQTY) < 3) {
// DO NOT INSERT INTO DB
}
else {
// insert after further scrubbing input
}
Read this: What's the best method for sanitizing user input with PHP?
Form validation is the process of checking if the form fields are filled in correct formats if they are processes. In your question, the correct format is "more than 3 characters". Of course, if statements are involved during form validations. In the client-side, you use JavaScript code to validate form fields.
Here is how it works: A form has an onsubmit event handler, when the user clicks Submit, or presses Enter, onsubmit will be triggered. onsubmit is where you put the form validation code.
<script>
function onsubmit() {
if (document.forms.mainForm.inputQTY.value.length < 3) {
alert("ERROR: Must be more than 3 characters");
return false; // stops the form submission
}
return true;
}
</script>
And here is how you add the onsubmit handler
...
The onsubmit function can return a value: true to let the form to be submitted, or false to stop the submission.
What is document.forms.mainForm.inputQTY.value.length? document.forms.mainForm references to the form named mainForm, while .inputQTY finds the inputQTY field.
You can use document.getElementsByTagName to manually find these elements, but it is [time and space]-consuming to write that type of code.
Because some users have JavaScript disabled, or crackers intentionally disable JS to bypass validation, you must validate server-side.
Server-side code will be something like this:
if (strlen($_GET['inputQTY']) < 3) {
echo "ERROR: Must be more than 3 characters";
} else {
// submit data
}
NOTE: code written from head, not tested
Related
I know there are many methods of validating forms on both client and server side but I was wondering what was the best practice?
Currently, I have Javascript functions validating form input fields 'on the fly' with onkeyup/onblur functions like so:
(Partial code:)
<p class="form-registerUserName">
<div class="upperLabel">
<label for="registerUserName">User Name</label>
<span class="required">*</span>
</div>
<input
id="registerUserName"
name="registerUserName"
type="text"
size="24"
maxlength="24"
value="<?php echo $_SESSION['registerUserName'];?>"
onkeyup="validateName()"
onblur="checkDuplicateName(); validateName()"
>
<label for="registerUserName" class="hint" id="registerUserNameHint"></label>
</p>
With Javascript functions like:
function validateName() {
userName = document.getElementById("registerUserName").value.trim();
re = /^[a-zA-Z0-9_]{1,30}$/;
if (userName==="") {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'required';
} else if (!re.test(userName)) {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'only alphanumeric characters and _';
} else {
document.getElementById("registerUserName").setAttribute("style","border-color: rgb(221,221,221) rgb(241,241,241) rgb(241,241,241) rgb(221,221,221);");
document.getElementById('registerUserNameHint').innerHTML = '';
}
} //validateName()
..So that the input box turns red and shows a hint on the side of the box if it does not validate.
So my question was - What is the best way to prevent the form from submission to my (Mysqli) database when the user hits submit?
(and second question..) Do I run an additional php server-side script after client-side validation has cleared?
Some ways I imagined to accomplish this is by having my Javascript functions set a Session variable that indicates an error condition, and not allow a submit if there was.
I am not certain how to do that, or how I set up my 'submit' to not work unless the error condition was cleared.
Would appreciate any help on that.
Then do I re-validate the same data (in the same manner) with php again, after a successful client-side validation before inserting into my database?
Thanks in advance.
First off, always do server-side validation!
Second, HTML5 form validation is well supported.
Examples: http://html5pattern.com/
You can then use CSS for validation styling.
Structure your validation with this logic:
if validateName() {
document.getElementById("myForm").submit();
}
// if returns true (passed validation) then submit
//validate on click of submit button or on submit
function validateName() {
userName = document.getElementById("registerUserName").value.trim();
re = /^[a-zA-Z0-9_]{1,30}$/;
if (userName==="") {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'required';
**return false;**
} else if (!re.test(userName)) {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'only alphanumeric characters and _';
**return false;**
........ so forth
else {
return true;
}
I have a signup form built with AngularJS using frontend and backend (with Express.js) input verification. Whenever a user enters an invalid email address, like qwidjq&/%, I'd like to show an error message and send the form back to the user. The email input field should contain the invalid email as the value.
The problem is that I cannot init input(type="email") fields with invalid email values. Only input(type="text") works. Here is an example.
Any ideas how to work around this restriction? I don't want to use input(type="text") and a custom directive. I'd like to keep input(type="email") as it changes keyboard layout on mobile devices.
Thanks in advance!
Perhaps display the bad text NEXT to the input element, e.g.
<input type="email" /><span id="emailerror">qidjq&/% is not a valid address</span>
You can initialise your input by initialising your model with data.
Example: http://plnkr.co/edit/TUJ6lv?p=preview
Unfortunately initializing a model to display invalid data would require patching AngularJS. In fact if you initialize any validated field with invalid data, it will appear blank.
Here is the code that is causing the email input to display blank without a valid email:
https://github.com/angular/angular.js/blob/master/src/ng/directive/input.js
(line 622)
var emailValidator = function(value) {
if (ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value)) {
ctrl.$setValidity('email', true);
return value;
} else {
ctrl.$setValidity('email', false);
return undefined;
}
};
Forgive me if I'm being stupid but can't you just disable the button on your form while the inputs are invalid. Alternatively, don't leave the form until you have had a positive response to your ajax request. If you get a negative response then show an error message. The data will still be in the form. I'm not familiar with Express.js so perhaps that is forcing you to refresh the form. I thought the whole point of using frameworks like Angular is to give you total control of the UI.
I'm working on designing a new process for internal job submission for work which now involves javascript for it to work effectively.
Scripting is not my forte but that hasn't deterred me, I've been able to find three different pieces of code to insert into the various buttons and fields and they've done what they should do. My problem is I need to combine some of these for an extra validation on submit. This is where I fall short.
The process:
There is a required field in the form which currently runs a custom validation script to check a certain format specific to the code needed for a job. This runs well and I was even able to add an alert and hint images that show when incorrect and a little tick when correct. Beautiful.
The second major part of the form is in the submit button. I hacked together a code which not only emails the submitted form with fields as the subject line but also makes all fields read only before doing so. Brilliant.
Here's the messy part. A user can enter a correct or incorrect required code and the validator does its bit but that doesn't stop them from still submitting the form. Fine. I can fix that by running the validator again on the submit button so it not only gives user feedback on blur of the required field but again validates on submit so if the field is incorrect the submit stops until the user has the correct value in the field. This is where my knowledge stops like a cliff edge and I can't seem to build a bridge.
I've tried numerous ways of calling the field value then just running the same validation script with some if and else statements but it just doesn't work.
Can anyone help? Current code for submission button below but keep in mind that the validation section of this code is also attached to the required field directly (this affects it?):
function OR_Stuff() {
var ProjectTitle = getField("ProjectTitle").value;
var Brand = getField("Brand").value;
var Name = getField("Name").value;
var Noosh = getField("INT_NooshCode").value;
for (var i = 0 ; i < this.numFields ; i++) {
var f = this.getField(this.getNthFieldName(i));
if (f.type != "Submit") // Change f.type to button name in form that the action is applied to
{
f.readonly = true;
}
}
this.mailDoc({
cTo: "email",
cBcc: "email",
cSubject: "NEW JOB: "+Brand+" - "+ProjectTitle+" - "+Noosh,
cMsg: "Thanks "+Name+" for sending through this job."
});
}
var re = /^\d{5}[A-Z]\d{2}$/
if (re.test(INT_NooshCode.value) == false) {
this.getField("RequiredAlert").display = display.visible;
this.getField("NooshTick").display = display.hidden;
app.alert("Sorry, we can't start a project without a Noosh code. \n\nPlease enter a valid Noosh code EG: 34256P02");
}
else {
OR_Stuff();
}
I'm using the Jquery Validation plugin to validate my form on the client before submitting.
There is a specific field in my form that I want to validate using ajax to the server, once the user has filled out that field (onblur).
(Basically it's the username field, I want to check on the server if the username is available and show a message accordingly)
Here is the code I'm using to validate my form:
$(document).ready(function()
{
$("#signupForm").validate({
submitHandler: ajaxSubmitForm});
});
(ajaxSubmitForm is just the js code that submits the form)
How can I use the Jquery Validation plugin to have the username field send its value to the server (using ajax) when it has changed and have the server return a result that somehow marks that field as valid on the client so the rest of the validation works?
Thanks
You can do this using the remote rule on that element. You'd apply like so:
$('#signupForm').validate({
rules: {
username: {
remote: 'check_username.php' // this is the service page that returns true/false
}
}
});
Then to trigger the validation on blur, you add the following:
$('input[name="username"]').on('blur', function() {
$('#signupForm').validate().element(this); // this triggers the single element validation
});
submitHandler won't fire until the form is submitted for the first time. If you want to check username uniqueness while the user is filling out the form for the first time, you'd need a separate function. The example below assumes you have a page that runs a SQL query to see if the provided username exists in the database, then returns a json string like "{taken:false}" if the username is unique
$('#yourForm [name="username"]').on('blur',function(){
var username = $(this).val();
$.get('check/username.php',{username:username},function(data) {
if(data.taken) {
// highlight the field and indicate that the username is already taken
}
},'json');
}
The specifics of the call to $.get would depend on how your backend is set up. But in general, the process would go:
user enters a username
user blurs out of field
$.get or $.ajax call is made to the server to check uniqueness of username
if the response from the server indicates that the username is not unique, handle your validation (higlight the field, add an X icon, etc) and either
prevent form submission until the username IS unique, or
let the form submit and return an error for duplicate username
UPDATE
If you want to create a new rule for the validation plugin, you can do something like:
function isUsernameUnique(username,field) {
var unique = false;
$.ajax({
url: 'path/to/usernameCheck/',
data: { username: username },
async: false,
success: function(data) { unique = data.unique; }
});
return unique;
}
$.validator.addMethod(
'uniqueUsername',
isUsernameUnique,
'That username is already in use. Please choose a unique username.'
);
Then, in your form's validate function:
$('#yourForm').validate({
...
rules: {
username: { uniqueUsername: true }
...
}
...
});
And, a separate blur function for your username field:
$('[name="username"]').on('blur',function(){
var unique = isUsernameUnique($(this).val(),$(this));
if(!unique) {
// handle error
}
});
This lets you reuse the same function for both your pre-submit validation and your validation plugin. However, I see two issues here:
1 - After your first submit, $.fn.validate() will eagerly validate your username field, meaning the blur event on the username field is no longer required. perhaps you can disable it after the first submit to prevent unnecessary ajax calls
2 - It's not 100% DRY, as you'll need to do your own error handling in the blur event handler
Sorry for this most likely simple question.
I am running a script on submission of the form (code below), but first I would like to validate the form (contains one text box which must be an email) before the code is executed.
The script below is taken from here to ensure the form data is passed along to the colorbox lightbox script. But i only want to run this if the form is validated. I don't know how to combine this with an email validation script. Help! At the moment i've got a script that validates email (dreamweaver's) and this running, this command still runs even if it doesn't validate and i am not sure how to edit it so it doesn't.
$(document).ready(function() {
$("input#SearchButton").colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize(); //alert(url+'?'+ser);
return url+'?'+ser;
}, innerWidth:"1280", innerHeight:"884px", iframe:true, scrolling:false});
});
Then I am using this to validate the form:
function MM_validateForm() { //v4.0
if (document.getElementById){
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
if (val) { nm=val.name; if ((val=val.value)!="") {
if (test.indexOf('isEmail')!=-1) { p=val.indexOf('#');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
} else if (test!='R') { num = parseFloat(val);
if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
min=test.substring(8,p); max=test.substring(p+1);
if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
} }} else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
} if (errors) alert('The following error(s) occurred:\n'+errors);
document.MM_returnValue = (errors == '');
} }
Thanks!!!!
The HTML for the tigger is:
<input name="submit" type="image" onclick="MM_validateForm('email','','RisEmail');return document.MM_returnValue" src="images/go-button.gif" alt="Go! Get quote now!" align="top" : id="SearchButton"/>
In a nutshell: I want to tigger the code in the first snippet if the form validates using the code in the second snippet that is called by the html even in the third code snippet, but not if it doesn't.
You didn't post your HTML so I don't know if you have an actual form or just an input field without an actual form tag.
Assuming the former, you need a submit event so you can validate the form and then, if validation failed, terminate the submission.
$('#my_form').submit(function() {
//validate - forget the whole thing if it fails
if (!$('#my_field').val()) return false;
//if we get this far, validation succeeded - do other stuff now
});
A form submission is halted any time the submit callback returns false (or fires event.preventDefault()).
Andrew is correct, it would help if you provided the html in order to establish what the event trigger will be. Having reviewed the jquery plugin 'colorbox' briefly, it appears the lightbox is bound to the selectors click event.
Assuming Andrew's answer, if the email address validates you would need to manually trigger the click event for the lightbox from within the submit handler for the form. The following code should suffice.
$('#my_form').on('submit', function(e){
//perform validation.
MM_validateForm('email','','RisEmail');
//check the document variable set by the validation.
if (!document.MM_returnValue)
{
//did not validate
}else{
//open the colorbox
var search_btn = $('input#search');
search_btn.colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize();
return url + '?' + ser;
},
innerWidth: "1280",
innerHeight: "884px",
iframe:true,
scrolling:false});
//manually trigger the click event
search_btn.trigger('click');
}
//in either instance, disable the default action to ensure the form does not follow through.
e.preventDefault();
});
Obviously you'll have to replace the css selector names with your own, and utilise the email validation script that you may or may not have.