How to validate that input in textbox follows certain format - javascript

I am trying to code a page to lookup tickets in our system. All tickets follow the following format (6 digits, the dash, followed by 6 more digits):
123456-789123
I have created an HTML form to ask for and redirect the user to the results:
<section class="is-search">
<form method="get" action="http://mytesturl.com/tickets/lookup/info.php">
<input type="text" class="text" name="ticket" placeholder="Search by Ticket #" />
</form>
</section>
Currently, if someone types in "potato", the form will submit and throw several errors as the API obviously cannot search on "potato" or anything else that does not follow the ticket format.
I have seen a few recommendations on using JavaScript, however, I have not been able to get my syntax correct for the ticket format and was curious if there was a better way to do this in PHP as I am not familiar with JS.
What would be the best way to verify that the input follows this format before submitting to the API?

Have you tried using regular expression(regex).
This might help...
http://php.net/manual/en/function.preg-match.php

Use regular expression to check the format right before you submit the form
//on click, when the form is about to be submitted
$("#submit").click(function (e){
//prevent the submission unlit we check for valid format
e.preventDefault();
//check for valid format using regular expression test
if(/([0-9]{6}\-[0-9]{6})/.test($("input[name=ticket]").val())){
//submit
$("#search-form").submit();
}
else{
//display error
alert("error");
$("input[name=ticket]").val("");
}
});
HERE IS AN EXAMPLE

Regular expressions should work for this, both in javascript and PHP, something like :
$('.text').on('change', function() {
if (this.value.match(/^[0-9]{6}\-[0-9]{6}$/)) {
alert('ok');
}else{
alert('not valid');
}
});
FIDDLE
As noted by Jason in the comments, javascript validation is for convenience only, and any user input should be validated again on the serverside.
EDIT:
If for some reason you need the validation part as well ?
$('.is-search form').on('submit', function(e) {
e.preventDefault();
if ($('.text', this).val().match(/^[0-9]{6}\-[0-9]{6}$/)) {
this.submit();
}else{
alert('not a valid ticket number')
}
});
FIDDLE

You can start with adding the HTML attribute pattern="\d{6}\-\d{6} into the input tag. Then consider adding JavaScript checks, to cover browsers that do not support pattern but have JavaScript enabled.

<input type="text" class="text" name="ticket" placeholder="Search by Ticket #" onchange="myFunction()" />
myFunction(){
var value = $(".text").val();
if (/([0-9]{6}\-[0-9]{6})/.test(value)) {
$("input[type=submit]").removeAttr("disabled");
} else {
$("input[type=submit]").attr("disabled", "disabled");
}
}
<?php
if (preg_match('/([0-9]{6}\-[0-9]{6})/', &_POST['ticket'])) {
//execute code
}

Related

Can't get my "code" validated by JavaScript

Okay, so for my school project I need to create a page that has a form to input a contest code in a certain format, use javascript to validate it and display a "sorry" message. I believe I have everything correct, but clearly I do not as I am here asking for help. It seems like every time I try to submit the code, the page just refreshes, and my JSFiddle test returns a wonky error. Any help would be appreciated. The code that I am using is below with two JSFiddle links, one with just my code, and one with all of my HTML and my JavaScripting:
<script type="text/javascript">
$('.code_input').on('submit', function(e) {
e.preventDefault();
if ($('.code', this).val().match(/^[0-9]{6}\-[0-9]{6}\-[a-z]$/)) {
alert('Sorry, you did not win.');
}else{
alert('Not a valid code. Please try again.')
}
}); // reference point
</script>
<section class="code_input">
<form method="post">
<input type="text" class="code" name="code" placeholder="Type Code Here" />
<input id="submit" type='submit' value='Check Number'>
</form>
</section>
JSFiddle - Just the code
JSFiddle - All the code
https://jsfiddle.net/azhzpLct/
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
if (document.querySelector('.code').value.match(/^[0-9]{6}\-[0-9]{6}\-[a-z]$/)) {
alert('Sorry, you did not win.');
}else{
alert('Not a valid code. Please try again.')
}
});

Need help to test html form textbox and go to page if value is the same as a set value

Hello I am trying to make a simple form to test if the the textfield is equal to a variable, variable value example: ( "MyPassword123" ).
Then if it the textfield is the same as the variable than go to html document, example: ( "nextPage.html" ).
however if its NOT equal to variable then go to html document, example: ( "index.html" ).
the reason of the password is to restrict people that don't play on my game server form nextPage.html, it will have just like news feeds and game information on it, Its nothing like an profile or anything I just want to give out a password to only allow people that play on the server to view a page that's all.
I have tried many times to get this to work in javascript and I am sure its achievable for this simple task using if/else statements and validate the name of the text field but I am no good at java nor javascript.
Form Code:
<form name="accessForm">
Password: <input type="text" name="inputCode"/>
<input type="submit" value="Submit"/>
</form>
If someone could post some code of javascript to make this work, you would so awesome.
NOTE:
Not sure if it matters much but I am using HTML5 and CSS3, and for
Hosting I will be using GoogleDrive, so I cant use MySQL, it needs to
be javascript. I have not tested Drive to see if it allows PHP but I
know Javascript works fine.
You need not to use HTML form for it
<script>
function checkIt()
{
if(document.getElementById("inputCode").value=="MyPassword123")
location.href="nextPage.html";
else
location.href="index.html";
}
</script>
Password: <input id="inputCode" type="text"/>
<input type="button" value="Submit" onclick="checkIt()"/>
Like #Wes Foster mentioned, you should do password validation on the backend, but to compare a form input to a variable in vanilla JS you could do this:
var password = "magicWord";
var form = document.getElementById("formName");
form.onsubmit = function(e) {
e.preventDefault();
var data = document.forms.accessForm.inputCode.value;
if (data == password) location.href = "success.html";
else location.href = "fail.html";
};

Validating user input using javascript

I'm trying to validate what a user enters into a texbox on the client-side, using javascript. I have also added a span close to my input tag like so,
<div>
<label for="fname">First Name*</label>
<input id="fname" name="fname" maxlength="30" type="text" /><span style="display:none;" id="fnameerror" name="fnameerror">*Please enter your firstname</span>
</div>
Here's the javascript code snippet validating the input,
if(document.getElementById('fname').value.length==0){
msg='Please enter your first name';
document.getElementById('fnameerror').style.display='inline';
document.getElementById('fnameerror').style.color='red';
valid=false;
}
What I want to achieve now is,
1) The textbox with the error should gain focus.
2) After the error message is displayed and the user enters a valid data, the error message should disappear.
How do I achieve this. I'm fairly new to javascript. Thanks.
Change your JS code:
document.getElementById('fname').onkeyup = function() {
if(document.getElementById('fname').value.length==0){
msg='Please enter your first name';
document.getElementById('fnameerror').style.display='inline';
document.getElementById('fnameerror').style.color='red';
valid=false;
document.getElementById('fname').focus();
} else {
valid=true;
document.getElementById('fnameerror').style.display='none';
}
}
Fiddle.
If you've read about HTML5, it allows you to add form validation as attribute fields directly instead of having to write code for it. It also presents things neatly. Have a look. This might help:
http://diveintohtml5.info/forms.html
I will suggest to use Jquery validator. Of course you need to include jquery,and jquery plugin, but you do not need time to write validation from the scratch only to implement what exist.

Check if promotion code exist and after redirect

I have a promotion page. I want that page to can be visited only by users that have a code from me sent by email.
So I have this form:
<form accept-charset="UTF-8" action="promotion.php" method="post" onSubmit="return checkcode(this);">
<input name="code" type="text" id="code" maxlength="15" placeholder="Confirmation Code" required="required" />
<input type="submit" value="Submit" />
</form>
And this Javascript:
function checkcode ( form )
{
var pattern = /name="code" value="|2222|1234|8888|"/g
if (!pattern.test(form.code.value)) {
alert( "The code is incorrect." );
form.code.focus();
return false ;
}
return true ;
}
This javascript code not functioning properly: if I write a bigger code with more characters will redirect; also I can't add many, if the numbers from value line come down when I write more codes/numbers will redirect, I need to add more than 100 codes. Is there any other way to get this to functioning properly? Maybe there is a PHP code that can read the codes from a file and redirect only if the code exist in that file?
And on JSFiddle redirect in any case, the javascript code just doesn't working. But if I upload on my server seems to work, but still has the error that I writed below. http://jsfiddle.net/focusoft/e9DHg/
Do like Akhil Sidharth suggests:
Make AJAX call to PHP page passing the promocode. Do validaton within the PHP and return true or false...
You do not need DB for this.
Oke, first thing, NEVER do validating like this in the javascript. This is visible for everyone! so UNSECURE! :)
How you should do this:
create a database table called codes with fields: code, email(if personal code) and code_active(boolean).
send the code (and email) using AJAX or just post it to the backend.
check in the backend if the code is valid and return true/false.
(if you don't want to use a database, then just hardcode the codes in a php array)
NO DATABASE:
<?php
$a_codes = array(1111,2222,3333,4444,5555);
if(isset($_POST['code'])){
if(in_array($_POST['code'], $a_codes)){
echo "VALID CODE";
}else{
echo "INVALID CODE";
}
}
?>
Please dont do this way, try to put all codes in DB & then using AJAX to validate the code will be a better idea. if validation success try making a changing a hidden input value to something for further population. Using JS like this is a very bad idea as its client side validation. please use server side validation.
check this code, if you use Jquery, it will shorten the code & make it better. I just used plain old simple Ajax.
index.php
<script type="text/javascript">
function GetXmlHttpObject(){
var xmlHttp=null;
try{
xmlHttp=new XMLHttpRequest();
}
catch (e){
// Internet Explorer
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function search_code(){
var parameter1= document.getElementById('code').value;
if (xmlHttps1==null){
alert ("Your browser does not support AJAX!");
return;
}
var url="ajax_validate.php?para1="+encodeURIComponent(parameter1)+"&search=search";
xmlHttps1.onreadystatechange=result_search_code;
xmlHttps1.open("GET",url,true);
xmlHttps1.send(null);
}
function result_search_code(){
if (xmlHttps1.readyState==4){
document.getElementById('Promotion_validation_Status').innerHTML="";
document.getElementById('Promotion_validation_Status').innerHTML=xmlHttps1.responseText;
}
}
var xmlHttps1=GetXmlHttpObject();
</script>
<form accept-charset="UTF-8" method="post" onSubmit="return validate()">
<input name="code" type="text" id="code" maxlength="15" placeholder="Confirmation Code" required="required" />
<input type="button" value="Submit" onClick="search_code()" />
</form>
<div id="Promotion_validation_Status" />
ajax_validate.php
<?php
if($_REQUEST['search']=='search'){
$promotion_code=mysql_real_escape_string($_REQUEST['para1']);
$sql="select count(*) from table where feild_name='".$promotion_code;
$res1=mysql_query($sql1);
$res1=mysql_fetch_array($res1);
if($res1['count(*)']>0){
echo "Sucess";
} else {
echo "Validation Failed";
}
}
?>
I think, this should give you an idea. Before you use ajax i will request to validate the format of your code using JS. so it will be easier for you to compare it with DB. This is just a basic outline for you to start this. There are so many things which i havent taken care of.
assuming your code and work, and just want to expand it.
You only need to change your regular expression.
/name="code" value="|2222|1234|8888|"/g
instead of this: |2222|1234|8888|
try this: [0-9]{4}
where: {number} (is the number of characters you admit)
this way you have a rando from 0000-9999 to validate codes.
name="code" value="[0-9]{4}"

Validate at least 1 file input is completed with jQuery

How can I ensure that at least one field has a selected file using jQuery? Here is my form:
<form action="b.php">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="submit" value="Value">
</form>
To achieve this you can use map() to build an array of all the valid file input elements. You can then check if this array has any elements in it. If it does, then at least one input was valid, if it was empty then nothing has been chosen. Try this:
var validFields = $('input[type="file"]').map(function() {
if ($(this).val() != "") {
return $(this);
}
}).get();
if (validFields.length) {
console.log("Form is valid");
} else {
console.log("Form is not valid");
}
Example fiddle
You could use jQuery's .val() method to check if a value has been set but I don't know if that works for file input types.
However, you should use a server-side language to validate your files because if you're using javascript, the person browsing the page can just disable the validating. Just loop through the file[] array and check if it's empty or not.
This is much safer and easier as well actually.
While you of course need server-side validation, there are some nice tricks to check if somebody has added a file to your input elements.
Now, your access to the file input element is heavily restricted due to security reasons, so you can't for example change it. You can, however, check the following:
if($('input[type="file"]').val() != "") {
alert("a file is selected")
}

Categories

Resources